-- Loom initial schema

CREATE TABLE projects (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name        TEXT NOT NULL,
    description TEXT,
    status      TEXT NOT NULL DEFAULT 'active',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE tasks (
    id          TEXT PRIMARY KEY,
    project_id  UUID NOT NULL REFERENCES projects(id),
    title       TEXT NOT NULL,
    status      TEXT NOT NULL DEFAULT 'pending',
    priority    TEXT NOT NULL DEFAULT 'p1',
    assignee    TEXT,
    parent_id   TEXT REFERENCES tasks(id),
    context     JSONB NOT NULL DEFAULT '{}',
    output      JSONB NOT NULL DEFAULT '{}',
    done_when   TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    claimed_at  TIMESTAMPTZ,
    done_at     TIMESTAMPTZ
);

CREATE TABLE task_deps (
    task_id     TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    depends_on  TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    PRIMARY KEY (task_id, depends_on)
);

CREATE TABLE events (
    id          BIGSERIAL PRIMARY KEY,
    project_id  UUID NOT NULL REFERENCES projects(id),
    event_type  TEXT NOT NULL,
    task_id     TEXT REFERENCES tasks(id),
    agent_id    TEXT,
    payload     JSONB NOT NULL DEFAULT '{}',
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE escalations (
    id          BIGSERIAL PRIMARY KEY,
    project_id  UUID NOT NULL REFERENCES projects(id),
    task_id     TEXT NOT NULL REFERENCES tasks(id),
    message     TEXT NOT NULL,
    resolved    BOOLEAN NOT NULL DEFAULT FALSE,
    resolved_at TIMESTAMPTZ,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE skill_runs (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id  UUID NOT NULL REFERENCES projects(id),
    skill_name  TEXT NOT NULL,
    inputs      JSONB NOT NULL DEFAULT '{}',
    output      JSONB NOT NULL DEFAULT '{}',
    model       TEXT,
    tokens_used INT,
    duration_ms INT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes
CREATE INDEX idx_tasks_project_status   ON tasks(project_id, status);
CREATE INDEX idx_tasks_status           ON tasks(status);
CREATE INDEX idx_tasks_assignee         ON tasks(assignee) WHERE assignee IS NOT NULL;
CREATE INDEX idx_task_deps_depends_on   ON task_deps(depends_on);
CREATE INDEX idx_events_project         ON events(project_id, created_at DESC);
CREATE INDEX idx_events_task            ON events(task_id, created_at DESC);
CREATE INDEX idx_escalations_unresolved ON escalations(project_id, resolved, created_at)
    WHERE resolved = FALSE;
