---Remove document references from servizio table
ALTER TABLE IF EXISTS public.servizio
DROP COLUMN IF EXISTS doc_personale_fronte_ref;

ALTER TABLE IF EXISTS public.servizio
DROP COLUMN IF EXISTS doc_personale_retro_ref;

---Add document references to users_anagrafica table
ALTER TABLE IF EXISTS public.users_anagrafica
ADD COLUMN doc_personale_fronte_ref UUID;

ALTER TABLE IF EXISTS public.users_anagrafica
ADD COLUMN doc_personale_retro_ref UUID;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'anagrafica_doc_fronte' 
        AND conrelid = 'public.users_anagrafica'::regclass
    ) THEN
        ALTER TABLE public.users_anagrafica
        ADD CONSTRAINT anagrafica_doc_fronte FOREIGN KEY (doc_personale_fronte_ref) 
        REFERENCES public.users_storage (user_storage_id) 
        MATCH SIMPLE ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'anagrafica_doc_retro' 
        AND conrelid = 'public.users_anagrafica'::regclass
    ) THEN
        ALTER TABLE public.users_anagrafica
        ADD CONSTRAINT anagrafica_doc_retro FOREIGN KEY (doc_personale_retro_ref) 
        REFERENCES public.users_storage (user_storage_id) 
        MATCH SIMPLE ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END $$;