-- Manual rollback for migration 011.
-- Refuses once equal bytes have been registered under multiple object identities.

BEGIN;

DO $$
BEGIN
    IF current_database() <> 'booking_test' THEN
        RAISE EXCEPTION
            'ARR artifact identity rollback is allowed only in booking_test';
    END IF;
    IF to_regclass('ingestion.artifacts_kind_hash_idx') IS NULL THEN
        RAISE EXCEPTION
            'ARR artifact identity migration is not applied';
    END IF;
    IF EXISTS (
        SELECT 1
        FROM ingestion.artifacts
        GROUP BY artifact_kind, sha256
        HAVING count(*) > 1
    ) THEN
        RAISE EXCEPTION
            'refusing rollback: repeated artifact content exists across storage identities';
    END IF;
END;
$$;

DROP INDEX ingestion.artifacts_kind_hash_idx;

ALTER TABLE ingestion.artifacts
    ADD CONSTRAINT artifacts_kind_hash_unique
    UNIQUE (artifact_kind, sha256);

COMMIT;
