-- Media Refs
CREATE TABLE IF NOT EXISTS public.media_refs (
    codice TEXT NOT NULL,
    ordine INTEGER NOT NULL,
    storage_id UUID NOT NULL,
    og_url TEXT NOT NULL,
    media_type TEXT NOT NULL CHECK (media_type IN ('image', 'video')),
    is_thumbnail BOOLEAN NOT NULL DEFAULT FALSE
);
-- Indexes
CREATE INDEX IF NOT EXISTS idx_media_refs_codice ON public.media_refs (codice);
CREATE INDEX IF NOT EXISTS idx_media_refs_storage_id ON public.media_refs (storage_id);
-- Unique Codice and Ordine
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'media_refs_unique'
) THEN
ALTER TABLE public.media_refs
ADD CONSTRAINT media_refs_unique UNIQUE (codice, ordine, is_thumbnail, media_type);
END IF;
END $$;

-- Foreign Key to Annunci
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'media_refs_annuncio'
) THEN
ALTER TABLE public.media_refs
ADD CONSTRAINT media_refs_annuncio FOREIGN KEY (codice) REFERENCES public.annunci (codice) ON UPDATE CASCADE ON DELETE CASCADE;
END IF;
END $$;

--Foreign Key to Storage
DO $$ BEGIN IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'media_refs_storage'
) THEN
ALTER TABLE public.media_refs
ADD CONSTRAINT media_refs_storage FOREIGN KEY (storage_id) REFERENCES public.storage (id) ON UPDATE CASCADE ON DELETE CASCADE;
END IF;
END $$;


DO $$
BEGIN
    IF EXISTS (
        SELECT FROM information_schema.tables 
        WHERE table_schema = 'public' 
          AND table_name   = 'media_refs'
    ) THEN
        EXECUTE '
            DELETE FROM public.storage s
            WHERE s.tag IS NOT NULL 
              AND NOT EXISTS (
                  SELECT 1 
                  FROM public.media_refs m 
                  WHERE s.id = m.storage_id
              );
        ';
    END IF;
END $$;

-- Drop Tables if they exist
DROP TABLE IF EXISTS public.images_refs;
DROP TABLE IF EXISTS public.videos_refs;