-- 153_proceeding_types_kind.down — t-paliad-325 / m/paliad#147
--
-- Best-effort rollback of mig 153. Restores the pre-mig state of
-- paliad.proceeding_types from the same-TX snapshot, drops the kind
-- column, drops the backstop trigger.

BEGIN;

SELECT set_config(
    'paliad.audit_reason',
    'mig 153 down: revert proceeding_types kind discriminator',
    true
);

-- ----------------------------------------------------------------
-- 1. Drop the backstop trigger + function.
-- ----------------------------------------------------------------

DROP TRIGGER IF EXISTS projects_proceeding_type_kind_check
    ON paliad.projects;

DROP FUNCTION IF EXISTS paliad.projects_proceeding_type_kind_check();

-- ----------------------------------------------------------------
-- 2. Restore is_active flags from the snapshot. We only touch rows
--    whose is_active value diverged from the snapshot — i.e. the 23
--    rows that mig 153 §4 deactivated.
-- ----------------------------------------------------------------

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

-- ----------------------------------------------------------------
-- 3. Drop the kind column (cascades the index).
-- ----------------------------------------------------------------

DROP INDEX IF EXISTS paliad.proceeding_types_kind_active_idx;

ALTER TABLE paliad.proceeding_types
    DROP COLUMN IF EXISTS kind;

-- ----------------------------------------------------------------
-- 4. Drop the snapshot table.
--    (The CHECK constraint on the kind column is dropped implicitly
--    when the column is dropped.)
-- ----------------------------------------------------------------

DROP TABLE IF EXISTS paliad.proceeding_types_pre_153;

COMMIT;
