-- 1. Create modulos table
CREATE TABLE IF NOT EXISTS public.modulos
(
    id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
    nombre character varying(100) COLLATE pg_catalog."default" NOT NULL,
    icono character varying(50) COLLATE pg_catalog."default",
    orden integer NOT NULL DEFAULT 0,
    activo boolean NOT NULL DEFAULT true,
    creado_en timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT modulos_pkey PRIMARY KEY (id)
);

-- 2. Insert unique module names from permisos into modulos
INSERT INTO public.modulos (nombre)
SELECT DISTINCT modulo FROM public.permisos
WHERE modulo IS NOT NULL AND modulo <> '';

-- 3. Add modulo_id column to permisos
ALTER TABLE public.permisos ADD COLUMN IF NOT EXISTS modulo_id integer;

-- 4. Update permisos.modulo_id based on matching names
UPDATE public.permisos p
SET modulo_id = m.id
FROM public.modulos m
WHERE p.modulo = m.nombre;

-- 5. Make modulo_id NOT NULL (after ensuring all are updated)
-- ALTER TABLE public.permisos ALTER COLUMN modulo_id SET NOT NULL;

-- 6. Add foreign key constraint
ALTER TABLE public.permisos
    ADD CONSTRAINT fk_permisos_modulos FOREIGN KEY (modulo_id)
    REFERENCES public.modulos (id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE CASCADE;

-- 7. Drop old modulo column
ALTER TABLE public.permisos DROP COLUMN IF EXISTS modulo;
