-- 151_dedupe_null_procedural_events (down) — t-paliad-319 / m/paliad#144
--
-- Best-effort restore from paliad.procedural_events_pre_151 and
-- paliad.sequencing_rules_pre_151. Re-points the reparented
-- sequencing_rules back at their original procedural_event_id and
-- reactivates the archived duplicates with the lifecycle_state +
-- is_active they had before the up migration.
--
-- Catastrophic-recovery path only; the normal revert is to leave the
-- dedupe in place (it is purely cosmetic).

-- 1. Re-point sequencing_rules.procedural_event_id back to its
--    pre-mig-151 value. The snapshot row is keyed by sr.id so the
--    join is 1:1 and idempotent.
UPDATE paliad.sequencing_rules sr
   SET procedural_event_id = s.original_procedural_event_id,
       updated_at          = now()
  FROM paliad.sequencing_rules_pre_151 s
 WHERE sr.id = s.id;

-- 2. Reactivate the archived duplicates with their snapshot lifecycle.
UPDATE paliad.procedural_events pe
   SET is_active       = s.is_active,
       lifecycle_state = s.lifecycle_state,
       updated_at      = now()
  FROM paliad.procedural_events_pre_151 s
 WHERE pe.id = s.id;

-- 3. Drop the snapshot tables — the data is back in place.
DROP TABLE IF EXISTS paliad.sequencing_rules_pre_151;
DROP TABLE IF EXISTS paliad.procedural_events_pre_151;
