-- 1. Create cargos_colaboradores table
CREATE TABLE IF NOT EXISTS public.cargos_colaboradores
(
    id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
    nombre character varying(100) COLLATE pg_catalog."default" NOT NULL,
    descripcion text COLLATE pg_catalog."default",
    activo boolean NOT NULL DEFAULT true,
    creado_en timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT cargos_colaboradores_pkey PRIMARY KEY (id)
);

-- 2. Insert unique cargos from colaboradores into cargos_colaboradores
INSERT INTO public.cargos_colaboradores (nombre)
SELECT DISTINCT cargo FROM public.colaboradores
WHERE cargo IS NOT NULL AND cargo <> '';

-- 3. Add cargo_id column to colaboradores
ALTER TABLE public.colaboradores ADD COLUMN IF NOT EXISTS cargo_id bigint;

-- 4. Update colaboradores.cargo_id based on matching names
UPDATE public.colaboradores c
SET cargo_id = cc.id
FROM public.cargos_colaboradores cc
WHERE c.cargo = cc.nombre;

-- 5. Add foreign key constraint
ALTER TABLE public.colaboradores
    ADD CONSTRAINT fk_colaboradores_cargos FOREIGN KEY (cargo_id)
    REFERENCES public.cargos_colaboradores (id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE CASCADE;

-- 6. Drop old cargo column
ALTER TABLE public.colaboradores DROP COLUMN IF EXISTS cargo;
