-- Sidelinja: Kalender-hendelser
-- Avhenger av: 0001_initial_schema.sql (nodes, workspaces)

BEGIN;

-- ============================================================
-- Kalendere (tilhører en workspace via nodes)
-- ============================================================

CREATE TABLE calendars (
    id          UUID PRIMARY KEY REFERENCES nodes(id) ON DELETE CASCADE,
    parent_id   UUID NOT NULL REFERENCES nodes(id),     -- Rot-node for workspace
    name        TEXT NOT NULL,
    color       TEXT,                                    -- Standard fargekode for hendelser
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ============================================================
-- Kalender-hendelser
-- ============================================================

CREATE TABLE calendar_events (
    id            UUID PRIMARY KEY REFERENCES nodes(id) ON DELETE CASCADE,
    calendar_id   UUID NOT NULL REFERENCES calendars(id) ON DELETE CASCADE,
    title         TEXT NOT NULL,
    description   TEXT,
    starts_at     TIMESTAMPTZ NOT NULL,
    ends_at       TIMESTAMPTZ,                           -- NULL = heldagshendelse uten sluttid
    all_day       BOOLEAN NOT NULL DEFAULT false,
    color         TEXT,                                   -- Overstyrer kalender-farge
    linked_node   UUID REFERENCES nodes(id) ON DELETE SET NULL,  -- Kobling til kanban-kort, episode, etc.
    created_by    TEXT REFERENCES users(authentik_id),
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_calendar_events_calendar ON calendar_events(calendar_id);
CREATE INDEX idx_calendar_events_time ON calendar_events(calendar_id, starts_at);

CREATE TRIGGER trg_calendar_events_updated_at BEFORE UPDATE ON calendar_events
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

-- ============================================================
-- Utvid node_type
-- ============================================================
-- NB: ALTER TYPE ... ADD VALUE kan ikke kjøres inne i transaksjon i PG < 16
-- Derfor committes dette etter hovedtransaksjonen

COMMIT;

ALTER TYPE node_type ADD VALUE IF NOT EXISTS 'calendar';
ALTER TYPE node_type ADD VALUE IF NOT EXISTS 'calendar_event';
