-- t-paliad-157 / m/paliad#15 follow-up: tag event_categories with the
-- coarse forums they belong to so the inbox-channel chip can narrow the
-- B1 cascade entry-points (the chip already narrows Pathway A's picker
-- and B2's fine-bucket forum filter; B1 was the last hold-out).
--
-- Allowed values: upc | de | epa | dpma. NULL = "neutral" — node stays
-- reachable from every inbox setting. Mixed-jurisdiction nodes (top-
-- level branches, generic court actions like Ladung / Kostenfestsetzung,
-- mündliche Verhandlung sub-states) intentionally stay NULL.
--
-- Two-step backfill:
--
--   1. Regex on slug for nodes that carry the forum token explicitly
--      (`upc-`, `.upc`, `-upc`, `.de-`, `-de-`, `.epa-`, `dpma`, …).
--      Tokens are bounded by `^` / dot / dash / `$` so e.g. `.dpma`
--      doesn't accidentally match the `de` rule.
--
--   2. Explicit slug list for stragglers whose name doesn't carry the
--      token (BGH / BPatG / Versäumnisurteil / Hinweisbeschluss are
--      DE-only; r116-eingaben is EPA-only).
--
-- Anything still NULL after both passes is intentionally neutral.

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

ALTER TABLE paliad.event_categories
    ADD CONSTRAINT event_categories_forums_check
    CHECK (forums IS NULL OR forums <@ ARRAY['upc','de','epa','dpma']::text[]);

COMMENT ON COLUMN paliad.event_categories.forums IS
    'Coarse forum tags driving the #15 inbox-channel chip narrowing. '
    'Allowed: upc, de, epa, dpma. NULL = neutral (visible from every '
    'inbox setting). Empty array is treated the same as NULL by the '
    'frontend filter (CHECK constraint allows it for forward '
    'compatibility but the migration writes NULL where neutral).';

CREATE INDEX event_categories_forums_gin
    ON paliad.event_categories USING GIN (forums)
    WHERE forums IS NOT NULL;

UPDATE paliad.event_categories SET forums = ARRAY['upc']
 WHERE forums IS NULL AND slug ~ '(^|[\.-])upc([\.-]|$)';

UPDATE paliad.event_categories SET forums = ARRAY['de']
 WHERE forums IS NULL AND slug ~ '(^|[\.-])de([\.-]|$)';

UPDATE paliad.event_categories SET forums = ARRAY['epa']
 WHERE forums IS NULL AND slug ~ '(^|[\.-])epa([\.-]|$)';

UPDATE paliad.event_categories SET forums = ARRAY['dpma']
 WHERE forums IS NULL AND slug ~ '(^|[\.-])dpma([\.-]|$)';

UPDATE paliad.event_categories SET forums = ARRAY['de']
 WHERE forums IS NULL AND slug IN (
    'beschluss-entscheidung.beschluss-bpatg-beschwerde',
    'beschluss-entscheidung.versaeumnisurteil',
    'cms-eingang.gericht.endentscheidung.beschluss-bpatg-beschwerde',
    'cms-eingang.gericht.endentscheidung.versaeumnisurteil',
    'cms-eingang.gericht.hinweisbeschluss',
    'ich-moechte-einreichen.berufung.bgh-rb',
    'ich-moechte-einreichen.berufung.bpatg-beschwerde'
);

UPDATE paliad.event_categories SET forums = ARRAY['epa']
 WHERE forums IS NULL
   AND slug = 'ich-moechte-einreichen.spaetere-schriftsaetze.r116-eingaben';
