-- 155_upc_apl_resplit.down — t-paliad-331 / m/paliad#149 Phase 2 P1
--
-- Best-effort rollback. Restores from the same-TX snapshots written by
-- mig 155. Drops the snapshots once restoration is verified.

BEGIN;

SELECT set_config(
    'paliad.audit_reason',
    'mig 155 down: revert upc.apl re-split (restore unified id=160)',
    true
);

-- ----------------------------------------------------------------
-- 1. Restore proceeding_types.is_active from snapshot.
-- ----------------------------------------------------------------

UPDATE paliad.proceeding_types pt
   SET is_active = pre.is_active
  FROM paliad.proceeding_types_pre_155 pre
 WHERE pt.id = pre.id
   AND pt.is_active IS DISTINCT FROM pre.is_active;

-- ----------------------------------------------------------------
-- 2. Restore rule bindings from snapshot.
-- ----------------------------------------------------------------

UPDATE paliad.sequencing_rules sr
   SET proceeding_type_id      = pre.proceeding_type_id,
       spawn_proceeding_type_id = pre.spawn_proceeding_type_id
  FROM paliad.sequencing_rules_pre_155 pre
 WHERE sr.id = pre.id
   AND (sr.proceeding_type_id      IS DISTINCT FROM pre.proceeding_type_id
        OR sr.spawn_proceeding_type_id IS DISTINCT FROM pre.spawn_proceeding_type_id);

-- ----------------------------------------------------------------
-- 3. Drop the snapshots.
-- ----------------------------------------------------------------

DROP TABLE IF EXISTS paliad.sequencing_rules_pre_155;
DROP TABLE IF EXISTS paliad.proceeding_types_pre_155;

COMMIT;
