-- events 도메인 PR-1 (6/11) — events 1차 컨테이너 테이블
-- 개인 운영 로그 / 일정 / 할 일 / 회고용 activity database 의 본체.
-- 기존 documents/tasks/ask_events 와 직교한 새 도메인.

CREATE TABLE IF NOT EXISTS events (
    id                BIGSERIAL PRIMARY KEY,
    title             TEXT NOT NULL,
    description       TEXT,                                  -- markdown
    kind              event_kind NOT NULL,
    status            event_status NOT NULL DEFAULT 'inbox',
    due_at            TIMESTAMPTZ,                           -- task 위주
    start_at          TIMESTAMPTZ,                           -- calendar_event 위주
    end_at            TIMESTAMPTZ,                           -- calendar_event 위주
    started_at        TIMESTAMPTZ,                           -- 실제 수행 시각 (activity_log 위주)
    ended_at          TIMESTAMPTZ,                           -- 실제 수행 종료
    all_day           BOOLEAN NOT NULL DEFAULT false,
    timezone          TEXT,
    defer_until       TIMESTAMPTZ,
    completed_at      TIMESTAMPTZ,
    cancelled_at      TIMESTAMPTZ,
    priority          SMALLINT CHECK (priority BETWEEN 1 AND 4),
    project_tag       VARCHAR(64),
    tags              JSONB NOT NULL DEFAULT '[]'::jsonb,
    source            event_source NOT NULL DEFAULT 'manual',
    source_ref        TEXT,                                  -- Message-ID 등 (TEXT, 충분한 길이)
    raw_metadata      JSONB NOT NULL DEFAULT '{}'::jsonb,
    memo_document_id  BIGINT REFERENCES documents(id) ON DELETE SET NULL,
    user_id           BIGINT NOT NULL REFERENCES users(id),
    created_by        event_actor NOT NULL DEFAULT 'manual',
    created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT now(),

    -- CHECK 제약 (라운드 10: task 제약 제거 + activity_log 완화 — 미래 확장 막지 않게)
    CONSTRAINT events_calendar_event_requires_start
        CHECK (kind <> 'calendar_event' OR start_at IS NOT NULL),
    CONSTRAINT events_activity_log_requires_time
        CHECK (kind <> 'activity_log' OR started_at IS NOT NULL OR ended_at IS NOT NULL)
);
