-- Allow the frozen manual-price manifest to be registered as an immutable
-- ingestion artifact. Migration 017 added the reference columns but did not
-- extend the pre-existing artifact-kind check.

BEGIN;

DO $$
DECLARE
    kind_check text;
BEGIN
    IF current_database() <> 'booking_test' THEN
        RAISE EXCEPTION
            'ARR manual-override artifact migration is allowed only in booking_test';
    END IF;
    IF to_regclass('ingestion.artifacts') IS NULL
       OR to_regclass('ingestion.daily_review_cases') IS NULL THEN
        RAISE EXCEPTION 'ARR migration 017 must be applied first';
    END IF;

    SELECT pg_get_constraintdef(oid)
    INTO kind_check
    FROM pg_constraint
    WHERE conrelid = 'ingestion.artifacts'::regclass
      AND conname = 'artifacts_artifact_kind_check';

    IF kind_check IS NULL THEN
        RAISE EXCEPTION 'ingestion artifact-kind constraint is missing';
    END IF;
    IF position('manual_override_json' IN kind_check) > 0 THEN
        RAISE EXCEPTION 'ARR migration 018 is already applied';
    END IF;
    IF EXISTS (
        SELECT 1
        FROM ingestion.artifacts
        WHERE artifact_kind NOT IN (
            'booking_source_md',
            'booking_excel',
            'opera_xml',
            'daily_xlsx',
            'monthly_xlsx',
            'channel_detail_xlsx',
            'company_ten_day_xlsx',
            'exception_xlsx',
            'result_json',
            'structured_result_json'
        )
    ) THEN
        RAISE EXCEPTION
            'unexpected artifact kind exists; refusing to replace its constraint';
    END IF;
END;
$$;

ALTER TABLE ingestion.artifacts
    DROP CONSTRAINT artifacts_artifact_kind_check;

ALTER TABLE ingestion.artifacts
    ADD CONSTRAINT artifacts_artifact_kind_check CHECK (artifact_kind IN (
        'booking_source_md',
        'booking_excel',
        'opera_xml',
        'daily_xlsx',
        'monthly_xlsx',
        'channel_detail_xlsx',
        'company_ten_day_xlsx',
        'exception_xlsx',
        'result_json',
        'structured_result_json',
        'manual_override_json'
    ));

COMMENT ON CONSTRAINT artifacts_artifact_kind_check ON ingestion.artifacts IS
  'Immutable ARR artifact roles, including frozen Daily manual-price manifests.';

COMMIT;
