-- Reverses 041_upc_counterclaim_cross_flows. Removes the new rules first,
-- then the new concepts, then restores the original sequence_order on the
-- existing UPC_INF / UPC_REV rows. Concept rows that are still referenced
-- elsewhere are kept (defensive — concepts may be reused by future
-- migrations).

DELETE FROM paliad.deadline_rules
 WHERE proceeding_type_id IN (
        SELECT id FROM paliad.proceeding_types WHERE code IN ('UPC_INF','UPC_REV')
       )
   AND code IN (
        'inf.def_to_ccr','inf.app_to_amend','inf.def_to_amend','inf.reply_def_ccr',
        'inf.reply_def_amd','inf.rejoin_reply_ccr','inf.rejoin_amd',
        'rev.app_to_amend','rev.def_to_amend','rev.reply_def_amd','rev.rejoin_amd',
        'rev.cc_inf','rev.def_cci','rev.reply_def_cci','rev.rejoin_cci'
       );

DELETE FROM paliad.deadline_concepts
 WHERE slug IN (
        'counterclaim-for-revocation','defence-to-counterclaim-for-revocation',
        'application-to-amend','defence-to-application-to-amend',
        'reply-to-defence-to-counterclaim-for-revocation',
        'reply-to-defence-to-application-to-amend',
        'rejoinder-on-reply-to-defence-to-ccr','rejoinder-on-reply-to-amend',
        'counterclaim-for-infringement','defence-to-counterclaim-for-infringement',
        'reply-to-defence-to-counterclaim-for-infringement',
        'rejoinder-on-counterclaim-for-infringement'
       )
   AND id NOT IN (SELECT concept_id FROM paliad.deadline_rules WHERE concept_id IS NOT NULL);

WITH proc AS (SELECT id FROM paliad.proceeding_types WHERE code = 'UPC_INF')
UPDATE paliad.deadline_rules dr
   SET sequence_order = CASE dr.code
       WHEN 'inf.soc'      THEN 0
       WHEN 'inf.sod'      THEN 1
       WHEN 'inf.reply'    THEN 2
       WHEN 'inf.rejoin'   THEN 3
       WHEN 'inf.interim'  THEN 4
       WHEN 'inf.oral'     THEN 5
       WHEN 'inf.decision' THEN 6
       WHEN 'inf.cost_app' THEN 7
       ELSE dr.sequence_order
   END
  FROM proc p
 WHERE dr.proceeding_type_id = p.id;

WITH proc AS (SELECT id FROM paliad.proceeding_types WHERE code = 'UPC_REV')
UPDATE paliad.deadline_rules dr
   SET sequence_order = CASE dr.code
       WHEN 'rev.app'      THEN 0
       WHEN 'rev.defence'  THEN 1
       WHEN 'rev.reply'    THEN 2
       WHEN 'rev.rejoin'   THEN 3
       WHEN 'rev.interim'  THEN 4
       WHEN 'rev.oral'     THEN 5
       WHEN 'rev.decision' THEN 6
       ELSE dr.sequence_order
   END
  FROM proc p
 WHERE dr.proceeding_type_id = p.id;
