-- mig 094 DOWN — restore the 7-digit CHECK and the snapshotted
-- pre-clear client_number / matter_number values from
-- paliad.projects_pre_094. Symmetric to the up migration.

SELECT set_config(
    'paliad.audit_reason',
    'mig 094 DOWN: restore 7-digit CHECK and pre-094 client_number/matter_number values from snapshot',
    true);

-- 1. Drop the 6-digit CHECKs.
ALTER TABLE paliad.projects
    DROP CONSTRAINT projekte_client_number_check,
    DROP CONSTRAINT projekte_matter_number_check;

-- 2. Restore the original values from the snapshot. Only rows that
--    existed at snapshot time are touched; rows added since stay as
--    they were.
UPDATE paliad.projects p
   SET client_number = s.client_number,
       matter_number = s.matter_number
  FROM paliad.projects_pre_094 s
 WHERE p.id = s.id;

-- 3. Re-add the legacy 7-digit CHECKs.
ALTER TABLE paliad.projects
    ADD CONSTRAINT projekte_client_number_check
        CHECK (client_number IS NULL OR client_number ~ '^[0-9]{7}$'),
    ADD CONSTRAINT projekte_matter_number_check
        CHECK (matter_number IS NULL OR matter_number ~ '^[0-9]{7}$');

-- 4. Drop the snapshot. The down migration is the only consumer.
DROP TABLE IF EXISTS paliad.projects_pre_094;
