-- Cube 数据助手只保存当前查询状态，不保存聊天消息历史。
CREATE TABLE IF NOT EXISTS ai_cube_report_states (
    dify_conversation_id VARCHAR(128) PRIMARY KEY,
    created_by UUID NOT NULL,
    title VARCHAR(200) NOT NULL DEFAULT '新数据对话',
    tenant_id VARCHAR(64) NOT NULL,
    tenant_name VARCHAR(200) NOT NULL DEFAULT '',
    current_cube JSONB NOT NULL,
    limit_source VARCHAR(16) NOT NULL DEFAULT 'system',
    response_message TEXT NOT NULL DEFAULT '',
    request_content TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT ck_ai_cube_report_states_limit_source
        CHECK (limit_source IN ('system', 'user'))
);

ALTER TABLE ai_cube_report_states
    ADD COLUMN IF NOT EXISTS request_content TEXT NOT NULL DEFAULT '';

CREATE INDEX IF NOT EXISTS idx_ai_cube_report_states_user_updated
    ON ai_cube_report_states (created_by, updated_at DESC);

COMMENT ON TABLE ai_cube_report_states IS 'Cube 数据助手当前查询状态；聊天历史由 Dify 保存';
COMMENT ON COLUMN ai_cube_report_states.current_cube IS '工作流最后一次成功返回的原始 Cube query';
COMMENT ON COLUMN ai_cube_report_states.limit_source IS 'system=系统预览限制，user=用户明确指定限制';
COMMENT ON COLUMN ai_cube_report_states.request_content IS '最近一次成功生成 Cube query 的用户需求';

CREATE TABLE IF NOT EXISTS ai_cube_saved_reports (
    id UUID PRIMARY KEY,
    dify_conversation_id VARCHAR(128) NOT NULL,
    created_by UUID NOT NULL,
    title VARCHAR(200) NOT NULL,
    requirement TEXT NOT NULL DEFAULT '',
    tenant_id VARCHAR(64) NOT NULL,
    tenant_name VARCHAR(200) NOT NULL DEFAULT '',
    cube_query JSONB NOT NULL,
    limit_source VARCHAR(16) NOT NULL DEFAULT 'system',
    response_message TEXT NOT NULL DEFAULT '',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_ai_cube_saved_reports_user_conversation
        UNIQUE (created_by, dify_conversation_id),
    CONSTRAINT ck_ai_cube_saved_reports_limit_source
        CHECK (limit_source IN ('system', 'user'))
);

CREATE INDEX IF NOT EXISTS idx_ai_cube_saved_reports_user_tenant_updated
    ON ai_cube_saved_reports (created_by, tenant_id, updated_at DESC);

COMMENT ON TABLE ai_cube_saved_reports IS '用户收藏的 Cube 报表；每个 Dify 会话最多收藏一个报表';
COMMENT ON COLUMN ai_cube_saved_reports.requirement IS '最近一次成功生成该报表的用户需求';
COMMENT ON COLUMN ai_cube_saved_reports.cube_query IS '收藏报表当前使用的原始 Cube query';
