-- t-paliad-195 down — reverses 091_drop_legacy_rule_columns.up.sql.
--
-- Restores the four columns and re-populates them from the
-- paliad.deadline_rules_pre_091 snapshot. Rules created AFTER the
-- mig 091 cutover (via the rule editor's POST /admin/api/rules)
-- won't have a snapshot entry — they get NULL on the restored
-- columns, which matches their original "never had these legacy
-- fields" state.
--
-- The snapshot table itself stays (it's a permanent audit artefact);
-- a focused follow-up slice / Slice 12 cleanup drops it once the
-- rule editor's migration-export flow has been used to roll any
-- post-drop edits back into version control.

SELECT set_config(
    'paliad.audit_reason',
    'rollback 091: restore legacy columns from pre-drop snapshot',
    true);

ALTER TABLE paliad.deadline_rules
    ADD COLUMN IF NOT EXISTS is_mandatory      boolean NOT NULL DEFAULT true,
    ADD COLUMN IF NOT EXISTS is_optional       boolean NOT NULL DEFAULT false,
    ADD COLUMN IF NOT EXISTS condition_flag    text[],
    ADD COLUMN IF NOT EXISTS condition_rule_id uuid;

UPDATE paliad.deadline_rules dr
   SET is_mandatory      = b.is_mandatory,
       is_optional       = b.is_optional,
       condition_flag    = b.condition_flag,
       condition_rule_id = b.condition_rule_id
  FROM paliad.deadline_rules_pre_091 b
 WHERE dr.id = b.id;
