CREATE TABLE IF NOT EXISTS public.media_storage (
    id uuid NOT NULL DEFAULT uuidv7(),
    created_at timestamp without time zone NOT NULL DEFAULT now(),
    filename text NOT NULL,
    mime_type text NOT NULL,
    file_size_bytes INT NOT NULL,
    file_data BYTEA NOT NULL,
    expires_at timestamp without time zone,
    tag text
);


DO $$ BEGIN IF EXISTS (
    SELECT
    FROM information_schema.columns
    WHERE table_name = 'media_storage'
        AND column_name = 'file_data'
) THEN
ALTER TABLE public.media_storage
    ALTER COLUMN file_data SET STORAGE EXTERNAL;
END IF;
END $$;

DO $$ BEGIN IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'media_storage_pkey'
        AND conrelid = 'public.media_storage'::regclass
) THEN
ALTER TABLE public.media_storage
ADD CONSTRAINT media_storage_pkey PRIMARY KEY (id);
END IF;
END $$;

DELETE FROM public.media_refs 
WHERE storage_id NOT IN (SELECT id FROM public.media_storage);

DELETE FROM public.storage 
WHERE tag is not null;

ALTER TABLE media_refs 
DROP CONSTRAINT IF EXISTS media_refs_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.media_storage (id) ON UPDATE CASCADE ON DELETE CASCADE;
END IF;
END $$;