-- Images_refs index
CREATE INDEX IF NOT EXISTS annunci_imgs ON images_refs (codice);

-- Videos_refs Table
CREATE TABLE IF NOT EXISTS public.videos_refs (
    codice TEXT COLLATE pg_catalog."default" NOT NULL,
    ordine integer NOT NULL,
    video TEXT COLLATE pg_catalog."default" NOT NULL,
    thumb TEXT COLLATE pg_catalog."default" NOT NULL,
    og_url TEXT COLLATE pg_catalog."default" NOT NULL
);

-- Unique Codice and Ordine for Videos_refs Table
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'video_cod_order'
        AND conrelid = 'public.videos_refs'::regclass
    ) THEN
        ALTER TABLE public.videos_refs
        ADD CONSTRAINT video_cod_order UNIQUE (codice, ordine);
    END IF;
END $$;

-- Foreign Key to Annunci for Videos_refs Table
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint 
        WHERE conname = 'cod_video'
        AND conrelid = 'public.videos_refs'::regclass
    ) THEN
        ALTER TABLE public.videos_refs 
        ADD CONSTRAINT cod_video 
        FOREIGN KEY (codice) REFERENCES public.annunci (codice) 
        ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $$;

-- Index for Videos_refs Table
CREATE INDEX IF NOT EXISTS annunci_videos ON videos_refs (codice);

-- Rename url_video to external_videos in Annunci Table
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_name='annunci' 
        AND column_name='url_video'
    ) THEN
        ALTER TABLE public.annunci 
        RENAME COLUMN url_video TO external_videos;

END IF;

END $$;