-- 000017: 深度研究任务表 + research_generator 应用类型

CREATE TABLE IF NOT EXISTS research_tasks (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id         UUID NOT NULL REFERENCES users(id),
    app_id          UUID REFERENCES applications(id),

    topic           TEXT NOT NULL,                 -- 研究题目/问题
    config          JSONB NOT NULL DEFAULT '{}',   -- {max_steps, max_sources, language, report_type}

    status          VARCHAR(30) NOT NULL DEFAULT 'pending'
                    CHECK (status IN (
                        'pending',        -- 等待处理
                        'planning',       -- 拆解问题
                        'searching',      -- 检索
                        'reading',        -- 抓取阅读与摘要
                        'synthesizing',   -- 合成报告
                        'completed',      -- 完成
                        'failed',         -- 失败
                        'canceled'        -- 已取消
                    )),
    progress        INTEGER NOT NULL DEFAULT 0 CHECK (progress BETWEEN 0 AND 100),
    status_message  TEXT,
    error_message   TEXT,

    report          TEXT,                          -- 最终 Markdown 报告
    sources         JSONB NOT NULL DEFAULT '[]',   -- 引用来源 [{title,url,snippet}]
    tokens_used     INTEGER NOT NULL DEFAULT 0,

    started_at      TIMESTAMPTZ,
    completed_at    TIMESTAMPTZ,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_research_tasks_user ON research_tasks(user_id);
CREATE INDEX IF NOT EXISTS idx_research_tasks_status ON research_tasks(status);
CREATE INDEX IF NOT EXISTS idx_research_tasks_created ON research_tasks(created_at DESC);

DROP TRIGGER IF EXISTS update_research_tasks_updated_at ON research_tasks;
CREATE TRIGGER update_research_tasks_updated_at
    BEFORE UPDATE ON research_tasks
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- 扩展应用类型，加入 research_generator（深度研究）
ALTER TABLE applications DROP CONSTRAINT IF EXISTS applications_dify_app_type_check;
ALTER TABLE applications ADD CONSTRAINT applications_dify_app_type_check
    CHECK (dify_app_type IN ('chatbot','completion','workflow','agent','ppt_generator','skill','research_generator'));
