-- t-paliad-173 — SmartTimeline Slice 2.
-- Two structural additions for click-to-anchor (§6 of
-- docs/design-smart-timeline-2026-05-08.md) + the layered SoC→SoD
-- sequence enforcement from m/paliad#31:
--
--   1. paliad.appointments.deadline_rule_id  — nullable FK to
--      paliad.deadline_rules. Court-set rules (Hauptverhandlung,
--      Decision, Order) anchor as appointments rather than deadlines
--      and need to remember which rule they came from so downstream
--      reflow has the parent_id chain.
--
--   2. paliad.deadlines.source CHECK         — adds 'anchor' alongside
--      the existing 'manual' / 'fristenrechner' values + the two
--      legacy values the design doc mentions ('rule', 'import') for
--      forward-compat. 'anchor' separates a click-to-anchor write from
--      a user-typed-it-in 'manual' write so analytics + a future
--      Outlook-import path can tell them apart.
--
-- paliad.project_events.event_type is intentionally NOT constrained —
-- the column is free-text in prod (every event_type today lives in
-- code, not in a CHECK). Slice 2 needs to write 'rule_skipped' rows
-- (§6.4); no schema change is required for that.
--
-- Idempotent: re-applying is a no-op. Tracker advances 75 → 76.

-- 1. paliad.appointments.deadline_rule_id ----------------------------------

ALTER TABLE paliad.appointments
    ADD COLUMN IF NOT EXISTS deadline_rule_id uuid NULL
        REFERENCES paliad.deadline_rules(id) ON DELETE SET NULL;

COMMENT ON COLUMN paliad.appointments.deadline_rule_id IS
    'When non-NULL, this appointment is the actual occurrence of a '
    'standard-course rule (Hauptverhandlung, Decision, Order). '
    'Anchors downstream re-projection via FristenrechnerService '
    'AnchorOverrides. See docs/design-smart-timeline-2026-05-08.md §6.';

CREATE INDEX IF NOT EXISTS appointments_deadline_rule_id_idx
    ON paliad.appointments (deadline_rule_id)
    WHERE deadline_rule_id IS NOT NULL;

-- 2. paliad.deadlines.source CHECK -----------------------------------------

DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM pg_constraint
         WHERE conname = 'deadlines_source_check'
           AND conrelid = 'paliad.deadlines'::regclass
    ) THEN
        ALTER TABLE paliad.deadlines DROP CONSTRAINT deadlines_source_check;
    END IF;
END $$;

ALTER TABLE paliad.deadlines
    ADD CONSTRAINT deadlines_source_check
    CHECK (source IN ('manual', 'fristenrechner', 'rule', 'import', 'anchor'));
