-- Reverses mig 097. Restores rule_code + legal_source on every row
-- touched by the backfill (and the rev.defence normalization) from the
-- paliad.deadline_rules_pre_097 snapshot, refreshes the deadline_search
-- materialized view, then drops the snapshot.
--
-- audit_reason wrapper required by the mig 079 audit trigger.

SELECT set_config(
    'paliad.audit_reason',
    'mig 097 (down): revert t-paliad-210 legal-citation backfill — restore rule_code/legal_source from deadline_rules_pre_097 snapshot',
    true);

-- =============================================================================
-- 1. Restore rule_code + legal_source from the pre_097 snapshot for every
--    row whose current values diverge from the snapshot. Symmetric across
--    the § 1 / § 2 / § 3 backfills and the § 5 rev.defence normalization
--    in one pass. If the snapshot table is missing (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_097'
    ) INTO v_snap_exists;

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

    UPDATE paliad.deadline_rules dr
       SET rule_code    = snap.rule_code,
           legal_source = snap.legal_source
      FROM paliad.deadline_rules_pre_097 snap
     WHERE dr.id = snap.id
       AND (dr.rule_code    IS DISTINCT FROM snap.rule_code
         OR dr.legal_source IS DISTINCT FROM snap.legal_source);
END $$;

-- =============================================================================
-- 2. Refresh deadline_search so the reverted rule_code / legal_source
--    values repopulate the materialized view.
-- =============================================================================

REFRESH MATERIALIZED VIEW paliad.deadline_search;

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

DROP TABLE IF EXISTS paliad.deadline_rules_pre_097;
