-- Reverses mig 095. Restores the 4 patched de_inf.* rows from
-- paliad.deadline_rules_pre_095 and removes the 4 new rules
-- (inf.prelim, rev.prelim, inf.appeal_spawn, rev.appeal_spawn).
--
-- The audit_reason is required by the mig 079 trigger for UPDATE +
-- DELETE; set_config at top supplies it.

SELECT set_config(
    'paliad.audit_reason',
    'mig 095 (down): revert t-paliad-205 fristen gap-fill — restore de_inf.* patches from deadline_rules_pre_095, delete 4 new rules',
    true);

-- =============================================================================
-- 1. Delete the 4 new rules. Idempotent — if a rule is already missing
--    the DELETE matches zero rows.
-- =============================================================================

DELETE FROM paliad.deadline_rules
 WHERE code IN ('inf.prelim', 'rev.prelim',
                'inf.appeal_spawn', 'rev.appeal_spawn')
   AND lifecycle_state = 'published';

-- =============================================================================
-- 2. Restore the 4 patched rows from the pre_095 snapshot. The snapshot
--    captured the rows at first up-migration run; the restore copies
--    each tracked field back. If the snapshot table doesn't exist (down
--    run before up), the restore is a no-op.
-- =============================================================================

DO $$
DECLARE
    v_snap_exists boolean;
BEGIN
    SELECT EXISTS (
        SELECT 1
          FROM information_schema.tables
         WHERE table_schema = 'paliad'
           AND table_name = 'deadline_rules_pre_095'
    ) INTO v_snap_exists;

    IF NOT v_snap_exists THEN
        RAISE NOTICE
            'mig 095 (down): snapshot table paliad.deadline_rules_pre_095 missing — nothing to restore';
        RETURN;
    END IF;

    UPDATE paliad.deadline_rules dr
       SET legal_source = snap.legal_source,
           is_court_set = snap.is_court_set,
           description  = snap.description,
           updated_at   = now()
      FROM paliad.deadline_rules_pre_095 snap
     WHERE dr.id = snap.id;
END $$;

-- =============================================================================
-- 3. Drop the snapshot table so a re-applied up migration captures a
--    fresh snapshot of the current state.
-- =============================================================================

DROP TABLE IF EXISTS paliad.deadline_rules_pre_095;
