-- ==========================================
-- Switchboard Core — 008 Tasks
-- ==========================================
-- Task scheduling and run history.
-- Stripped: persona_id (kept nullable, no FK), output_channel_id,
-- provider_config_id. Output modes: notification | webhook | log.
-- ==========================================

CREATE TABLE IF NOT EXISTS tasks (
    id                 UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    owner_id           UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    team_id            UUID REFERENCES teams(id) ON DELETE SET NULL,
    name               TEXT NOT NULL,
    description        TEXT DEFAULT '',
    scope              TEXT NOT NULL DEFAULT 'personal'
                       CHECK (scope IN ('personal', 'team', 'global')),
    task_type          TEXT NOT NULL DEFAULT 'action'
                       CHECK (task_type IN ('action', 'workflow', 'system')),
    system_function    TEXT DEFAULT '',
    persona_id         TEXT,
    model_id           TEXT,
    system_prompt      TEXT DEFAULT '',
    user_prompt        TEXT DEFAULT '',
    workflow_id        UUID REFERENCES workflows(id) ON DELETE SET NULL,
    tool_grants        JSONB,
    schedule           TEXT NOT NULL,
    timezone           TEXT NOT NULL DEFAULT 'UTC',
    is_active          BOOLEAN NOT NULL DEFAULT true,
    trigger_token      TEXT UNIQUE,
    max_tokens         INTEGER NOT NULL DEFAULT 4096,
    max_tool_calls     INTEGER NOT NULL DEFAULT 10,
    max_wall_clock     INTEGER NOT NULL DEFAULT 300,
    output_mode        TEXT NOT NULL DEFAULT 'log'
                       CHECK (output_mode IN ('notification', 'webhook', 'log')),
    webhook_url        TEXT,
    webhook_secret     TEXT,
    notify_on_complete BOOLEAN NOT NULL DEFAULT false,
    notify_on_failure  BOOLEAN NOT NULL DEFAULT true,
    last_run_at        TIMESTAMPTZ,
    next_run_at        TIMESTAMPTZ,
    run_count          INTEGER NOT NULL DEFAULT 0,
    created_at         TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at         TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_tasks_next_run ON tasks(next_run_at) WHERE is_active = true;
CREATE INDEX IF NOT EXISTS idx_tasks_owner ON tasks(owner_id);
CREATE INDEX IF NOT EXISTS idx_tasks_team ON tasks(team_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_tasks_trigger_token
    ON tasks(trigger_token) WHERE trigger_token IS NOT NULL;

-- ── Task Runs ───────────────────────────────

CREATE TABLE IF NOT EXISTS task_runs (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    task_id          UUID NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    status           TEXT NOT NULL DEFAULT 'running'
                     CHECK (status IN ('queued', 'running', 'completed', 'failed', 'budget_exceeded', 'cancelled')),
    trigger_payload  TEXT,
    started_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    completed_at     TIMESTAMPTZ,
    tokens_used      INTEGER DEFAULT 0,
    tool_calls       INTEGER DEFAULT 0,
    wall_clock       INTEGER DEFAULT 0,
    error            TEXT
);

CREATE INDEX IF NOT EXISTS idx_task_runs_task ON task_runs(task_id);
CREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(task_id, status);
