-- Ordini Type
DO $$ BEGIN
CREATE TYPE public."OrderTypeEnum" AS ENUM (
    'Acconto',
    'Saldo',
    'Consulenza',
    'Altro'
);
EXCEPTION
    WHEN duplicate_object THEN NULL;
END $$;
-- Ordini Table
CREATE TABLE IF NOT EXISTS public.ordini (
    ordine_id UUID DEFAULT gen_random_uuid () NOT NULL,
    userid UUID NOT NULL,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL,
    packid TEXT NOT NULL,
    servizio_id UUID NOT NULL,
    type public."OrderTypeEnum" NOT NULL,
    "isActive" boolean DEFAULT FALSE NOT NULL
);
-- Primary Key
DO $$ BEGIN
ALTER TABLE public.ordini 
ADD CONSTRAINT ordini2_pkey PRIMARY KEY (ordine_id);
    EXCEPTION   
        WHEN invalid_table_definition THEN 
            RAISE NOTICE 'Primary key already exists. Ignoring...';
END $$;
-- Foreign Key to Prezziario
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'ordine_pack_fkey'
    ) THEN
        ALTER TABLE public.ordini 
        ADD CONSTRAINT ordine_pack_fkey 
        FOREIGN KEY (packid) REFERENCES public.prezziario (idprezziario) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;
-- Foreign Key to Servizio
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'ordine_servizio_fkey'
    ) THEN
        ALTER TABLE public.ordini 
        ADD CONSTRAINT ordine_servizio_fkey 
        FOREIGN KEY (servizio_id) REFERENCES public.servizio (servizio_id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;
-- Foreign Key to Users
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'ordine_userid_fkey'
    ) THEN
        ALTER TABLE public.ordini 
        ADD CONSTRAINT ordine_userid_fkey 
        FOREIGN KEY (userid) REFERENCES public.users (id) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;