-- 134_berufung_unification — DOWN
--
-- Reverses the Berufung unification: un-archives the 3 old appeal
-- proceeding_types, points the 16 rules back at their original
-- proceeding by their applies_to_target stamp, drops the new
-- upc.apl row, drops the two columns + their CHECK constraints.
--
-- The 3 old proceeding_types are recovered by code (we archived them,
-- never deleted them — that's what makes this down-migration safe).
-- ---------------------------------------------------------------

-- ---------------------------------------------------------------
-- 0. Audit reason (required by mig 079 trigger — step 2 UPDATEs
--    paliad.deadline_rules to reverse the reassignment).
-- ---------------------------------------------------------------

SELECT set_config(
    'paliad.audit_reason',
    'mig 134 DOWN: revert Slice B1 — restore 3 separate UPC appeal proceeding_types, drop applies_to_target column',
    true);

-- ---------------------------------------------------------------
-- 1. Un-archive the 3 old appeal proceeding_types.
-- ---------------------------------------------------------------

UPDATE paliad.proceeding_types
   SET is_active = true
 WHERE code IN ('upc.apl.merits', 'upc.apl.cost', 'upc.apl.order');

-- ---------------------------------------------------------------
-- 2. Point rules back at their original proceeding_type by stamp.
-- ---------------------------------------------------------------

UPDATE paliad.deadline_rules dr
   SET proceeding_type_id = (
        SELECT id FROM paliad.proceeding_types WHERE code = 'upc.apl.merits'
       )
 WHERE dr.applies_to_target = ARRAY['endentscheidung']::text[];

UPDATE paliad.deadline_rules dr
   SET proceeding_type_id = (
        SELECT id FROM paliad.proceeding_types WHERE code = 'upc.apl.cost'
       )
 WHERE dr.applies_to_target = ARRAY['kostenentscheidung']::text[];

UPDATE paliad.deadline_rules dr
   SET proceeding_type_id = (
        SELECT id FROM paliad.proceeding_types WHERE code = 'upc.apl.order'
       )
 WHERE dr.applies_to_target = ARRAY['anordnung']::text[];

-- ---------------------------------------------------------------
-- 3. Drop the unified upc.apl.unified row (now orphaned).
-- ---------------------------------------------------------------

DELETE FROM paliad.proceeding_types WHERE code = 'upc.apl.unified';

-- ---------------------------------------------------------------
-- 4. Drop the new columns + their CHECK constraints.
-- ---------------------------------------------------------------

ALTER TABLE paliad.deadline_rules
    DROP CONSTRAINT IF EXISTS deadline_rules_applies_to_target_chk;

ALTER TABLE paliad.deadline_rules
    DROP COLUMN IF EXISTS applies_to_target;

ALTER TABLE paliad.proceeding_types
    DROP CONSTRAINT IF EXISTS proceeding_types_appeal_target_chk;

ALTER TABLE paliad.proceeding_types
    DROP COLUMN IF EXISTS appeal_target;
