CREATE TABLE IF NOT EXISTS agent_task
(
    id             BIGSERIAL PRIMARY KEY,
    project_uuid   UUID         NOT NULL,
    -- Root task vs sub-task: parent_id NULL = root task
    parent_id      BIGINT,
    -- The AI that owns this task (optional, for sub-agent spawned tasks)
    agent_type     VARCHAR(20)  NOT NULL DEFAULT 'react',
    -- Status: pending / running / done / failed
    status         VARCHAR(20)  NOT NULL DEFAULT 'pending',
    -- Task description / goal
    title          VARCHAR(255),
    input          TEXT         NOT NULL,
    -- Final output (populated when status = done)
    output         TEXT,
    -- Error message (populated when status = failed)
    error          TEXT,
    -- Who initiated this task
    created_by     UUID,
    created_at     TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at     TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    started_at     TIMESTAMPTZ,
    done_at        TIMESTAMPTZ,
    -- Progress info (step count, current status text)
    progress       VARCHAR(255),
    -- Parent task FK
    CONSTRAINT fk_agent_task_parent FOREIGN KEY (parent_id) REFERENCES agent_task(id) ON DELETE SET NULL
);

CREATE INDEX IF NOT EXISTS idx_agent_task_project ON agent_task (project_uuid);
CREATE INDEX IF NOT EXISTS idx_agent_task_parent ON agent_task (parent_id);
CREATE INDEX IF NOT EXISTS idx_agent_task_status ON agent_task (status);
CREATE INDEX IF NOT EXISTS idx_agent_task_created_by ON agent_task (created_by);
CREATE INDEX IF NOT EXISTS idx_agent_task_created_at ON agent_task (created_at);
