-- 138_appeal_target_backfill_merits_order DOWN — t-paliad-303, m/paliad#134
--
-- Removes 'schadensbemessung' from the merits-track rules and
-- 'bucheinsicht' from the order-track rules, restoring the pre-137
-- shape (endentscheidung-only / anordnung-only / kostenentscheidung-only).

-- ---------------------------------------------------------------
-- 0. Audit reason (required by mig 079 trigger for any UPDATE on
--    paliad.deadline_rules).
-- ---------------------------------------------------------------

SELECT set_config(
    'paliad.audit_reason',
    'mig 138 DOWN: t-paliad-303 — strip Schadensbemessung/Bucheinsicht from applies_to_target per m/paliad#134',
    true);

-- ---------------------------------------------------------------
-- 1. Strip new targets via array_remove.
--
-- WHERE clauses pinned to upc.apl.unified to avoid touching unrelated
-- rules that might have been added later under other proceeding types.
-- ---------------------------------------------------------------

-- 1a. Remove schadensbemessung from merits-track rows.
UPDATE paliad.deadline_rules dr
   SET applies_to_target = array_remove(dr.applies_to_target, 'schadensbemessung')
  FROM paliad.proceeding_types pt
 WHERE pt.id = dr.proceeding_type_id
   AND pt.code = 'upc.apl.unified'
   AND dr.is_active = true
   AND 'schadensbemessung' = ANY(dr.applies_to_target);

-- 1b. Remove bucheinsicht from order-track rows.
UPDATE paliad.deadline_rules dr
   SET applies_to_target = array_remove(dr.applies_to_target, 'bucheinsicht')
  FROM paliad.proceeding_types pt
 WHERE pt.id = dr.proceeding_type_id
   AND pt.code = 'upc.apl.unified'
   AND dr.is_active = true
   AND 'bucheinsicht' = ANY(dr.applies_to_target);

-- ---------------------------------------------------------------
-- 2. Sanity check — no row may carry the new targets after the down.
-- ---------------------------------------------------------------

DO $$
DECLARE
    schad_left int;
    buch_left int;
BEGIN
    SELECT COUNT(*) INTO schad_left
      FROM paliad.deadline_rules dr
      JOIN paliad.proceeding_types pt ON pt.id = dr.proceeding_type_id
     WHERE pt.code = 'upc.apl.unified'
       AND dr.is_active = true
       AND 'schadensbemessung' = ANY(dr.applies_to_target);
    SELECT COUNT(*) INTO buch_left
      FROM paliad.deadline_rules dr
      JOIN paliad.proceeding_types pt ON pt.id = dr.proceeding_type_id
     WHERE pt.code = 'upc.apl.unified'
       AND dr.is_active = true
       AND 'bucheinsicht' = ANY(dr.applies_to_target);

    IF schad_left > 0 THEN
        RAISE EXCEPTION '[mig 138 DOWN] FAILED — % rows still carry schadensbemessung', schad_left;
    END IF;
    IF buch_left > 0 THEN
        RAISE EXCEPTION '[mig 138 DOWN] FAILED — % rows still carry bucheinsicht', buch_left;
    END IF;
    RAISE NOTICE '[mig 138 DOWN] stripped schadensbemessung + bucheinsicht from upc.apl.unified rules';
END $$;
