-- t-paliad-157 / m's 2026-05-08 Determinator Slice 3c: tag the
-- "ich möchte einreichen" cascade leaves with the role they imply so
-- the perspective chip in the B1 panel can hide options that don't
-- match the user's side. Klägerseite never files Klageerwiderung;
-- Beklagtenseite never files Klageschrift.
--
-- Allowed values: claimant | defendant | both | court. NULL stays
-- neutral (visible from every perspective). Most cms-eingang.* and
-- frist-verpasst.* leaves stay NULL because the user can be on either
-- side and still receive the same court communication.
--
-- Conservative backfill — only the obvious cases:
--   claimant   = files Klage / Replik
--   defendant  = files Widerklage / Duplik
--
-- Cross-appeal / Anschlussberufung / Reply-to-cross-appeal stay NULL
-- because the role flips depending on who appealed first; the user
-- needs context the cascade doesn't have. Tag those in a follow-up
-- once the perspective UI is dogfooded.

ALTER TABLE paliad.event_categories
    ADD COLUMN party text[];

ALTER TABLE paliad.event_categories
    ADD CONSTRAINT event_categories_party_check
    CHECK (party IS NULL OR party <@ ARRAY['claimant','defendant','both','court']::text[]);

COMMENT ON COLUMN paliad.event_categories.party IS
    'Coarse party tags for the #15 perspective chip on the B1 panel '
    '(Slice 3c). Allowed: claimant, defendant, both, court. NULL = '
    'neutral (visible from every perspective). When set, the cascade '
    'hides the node under perspectives that don''t include any of the '
    'tags.';

CREATE INDEX event_categories_party_gin
    ON paliad.event_categories USING GIN (party)
    WHERE party IS NOT NULL;

-- Claimant: files the action (Klage) or replies to defence (Replik).
UPDATE paliad.event_categories SET party = ARRAY['claimant']
 WHERE forums IS NOT NULL  -- skip the universal "Keine Akte" / "Sonstiges" stragglers
   AND (
       slug LIKE 'ich-moechte-einreichen.klage.%'
    OR slug LIKE 'ich-moechte-einreichen.spaetere-schriftsaetze.replik-%'
   );

-- Defendant: files the counter-claim (Widerklage) or rejoinder (Duplik).
UPDATE paliad.event_categories SET party = ARRAY['defendant']
 WHERE forums IS NOT NULL
   AND (
       slug LIKE 'ich-moechte-einreichen.widerklage.%'
    OR slug LIKE 'ich-moechte-einreichen.spaetere-schriftsaetze.duplik-%'
   );
