-- Phase A: reference tables (proceeding_types, deadline_rules, holidays).
-- These hold no user data. Readable by any authenticated user.

-- ============================================================================
-- proceeding_types
-- ============================================================================
CREATE TABLE paliad.proceeding_types (
    id              serial PRIMARY KEY,
    code            text NOT NULL UNIQUE,
    name            text NOT NULL,
    description     text,
    jurisdiction    text,
    category        text,
    default_color   text NOT NULL DEFAULT '#3b82f6',
    sort_order      integer NOT NULL DEFAULT 0,
    is_active       boolean NOT NULL DEFAULT true
);

-- ============================================================================
-- deadline_rules (tree of UPC + ZPO proceeding rules)
-- ============================================================================
CREATE TABLE paliad.deadline_rules (
    id                  uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    proceeding_type_id  integer REFERENCES paliad.proceeding_types(id) ON DELETE CASCADE,
    parent_id           uuid REFERENCES paliad.deadline_rules(id) ON DELETE SET NULL,
    code                text,
    name                text NOT NULL,
    description         text,
    primary_party       text,
    event_type          text,
    is_mandatory        boolean NOT NULL DEFAULT true,
    duration_value      integer NOT NULL DEFAULT 0,
    duration_unit       text NOT NULL DEFAULT 'months',
    timing              text DEFAULT 'after',
    rule_code           text,
    deadline_notes      text,
    sequence_order      integer NOT NULL DEFAULT 0,
    condition_rule_id   uuid REFERENCES paliad.deadline_rules(id) ON DELETE SET NULL,
    alt_duration_value  integer,
    alt_duration_unit   text,
    alt_rule_code       text,
    is_spawn            boolean NOT NULL DEFAULT false,
    spawn_label         text,
    is_active           boolean NOT NULL DEFAULT true,
    created_at          timestamptz NOT NULL DEFAULT now(),
    updated_at          timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX deadline_rules_proceeding_type_idx ON paliad.deadline_rules (proceeding_type_id);
CREATE INDEX deadline_rules_parent_idx          ON paliad.deadline_rules (parent_id);

-- ============================================================================
-- holidays (DE federal + UPC judicial vacations + other closures)
-- ============================================================================
CREATE TABLE paliad.holidays (
    id              serial PRIMARY KEY,
    date            date NOT NULL,
    name            text NOT NULL,
    country         text NOT NULL DEFAULT 'DE',
    state           text,
    holiday_type    text NOT NULL DEFAULT 'public_holiday'
                    CHECK (holiday_type IN ('public_holiday', 'closure', 'vacation')),
    UNIQUE (date, name, country)
);

CREATE INDEX holidays_date_idx ON paliad.holidays (date);
