-- Roll back monthly publication metadata only before it contains report or local-artifact data.

BEGIN;

DO $$
BEGIN
    IF current_database() <> 'booking_test' THEN
        RAISE EXCEPTION
            'ARR monthly publication rollback is allowed only in booking_test';
    END IF;
    IF to_regnamespace('reporting') IS NULL THEN
        RAISE EXCEPTION
            'ARR monthly publication migration is not applied';
    END IF;
    IF EXISTS (SELECT 1 FROM reporting.monthly_runs)
       OR EXISTS (
            SELECT 1
            FROM ingestion.artifacts
            WHERE storage_provider = 'local'
       ) THEN
        RAISE EXCEPTION
            'refusing rollback: monthly publication or controlled local artifact data exists';
    END IF;
END;
$$;

DROP SCHEMA reporting CASCADE;

ALTER TABLE ingestion.artifacts
    DROP CONSTRAINT artifacts_storage_provider_check;

ALTER TABLE ingestion.artifacts
    ADD CONSTRAINT artifacts_storage_provider_check CHECK (
        storage_provider IN ('oss', 's3', 'local_fixture')
    );

COMMIT;
