-- Preserve the browser-supplied XML basename separately from the canonical source artifact name.
-- PostgreSQL 15+. Migrations 008-012 remain immutable.

BEGIN;

DO $$
BEGIN
    IF current_database() <> 'booking_test' THEN
        RAISE EXCEPTION
            'ARR daily upload filename migration is allowed only in booking_test';
    END IF;
    IF to_regclass('ingestion.processing_runs') IS NULL
       OR to_regclass('reporting.monthly_runs') IS NULL THEN
        RAISE EXCEPTION
            'ARR migrations 008 through 012 must be applied first';
    END IF;
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'ingestion'
          AND table_name = 'processing_runs'
          AND column_name = 'uploaded_filename'
    ) THEN
        RAISE EXCEPTION
            'ARR daily upload filename migration is already applied';
    END IF;
END;
$$;

ALTER TABLE ingestion.processing_runs
    ADD COLUMN uploaded_filename text;

ALTER TABLE ingestion.processing_runs
    ADD CONSTRAINT processing_runs_uploaded_filename_check CHECK (
        uploaded_filename IS NULL
        OR (
            char_length(uploaded_filename) BETWEEN 1 AND 255
            AND uploaded_filename NOT IN ('.', '..')
            AND uploaded_filename !~ '[[:cntrl:]/\\]'
            AND right(lower(uploaded_filename), 4) = '.xml'
        )
    );

COMMENT ON COLUMN ingestion.processing_runs.uploaded_filename IS
  'Validated browser-supplied XML basename for user-facing provenance; NULL on historical runs. Internal source artifacts remain source.xml.';

COMMIT;
