-- Remove document references from servizio table
DO $$ BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'servizio_doc_fronte' 
        AND conrelid = 'public.servizio'::regclass
    ) THEN
        ALTER TABLE public.servizio DROP CONSTRAINT servizio_doc_fronte;
    END IF;
END $$;

DO $$ BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'servizio_doc_retro' 
        AND conrelid = 'public.servizio'::regclass
    ) THEN
        ALTER TABLE public.servizio DROP CONSTRAINT servizio_doc_retro;
    END IF;
END $$;

DO $$ BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_schema = 'public' 
        AND table_name = 'servizio' 
        AND column_name = 'doc_personale_fronte_ref'
    ) THEN
        ALTER TABLE public.servizio DROP COLUMN doc_personale_fronte_ref;
    END IF;
END $$;

DO $$ BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_schema = 'public' 
        AND table_name = 'servizio' 
        AND column_name = 'doc_personale_retro_ref'
    ) THEN
        ALTER TABLE public.servizio DROP COLUMN doc_personale_retro_ref;
    END IF;
END $$;

-- Add document references to users_anagrafica table
DO $$ BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_schema = 'public' 
        AND table_name = 'users_anagrafica' 
        AND column_name = 'doc_personale_fronte_ref'
    ) THEN
        ALTER TABLE public.users_anagrafica ADD COLUMN doc_personale_fronte_ref UUID;
    END IF;
END $$;

DO $$ BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_schema = 'public' 
        AND table_name = 'users_anagrafica' 
        AND column_name = 'doc_personale_retro_ref'
    ) THEN
        ALTER TABLE public.users_anagrafica ADD COLUMN doc_personale_retro_ref UUID;
    END IF;
END $$;

-- Add foreign key constraints
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) 
        ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END $$;

DO $$ BEGIN
    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) 
        ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END $$;