-- ============================================================
-- P5 AI 集成层：创建 AI 对话、消息、缓存三张表
-- 需求: 1.1, 1.2, 1.3, 1.4, 1.5
-- ============================================================

-- 1. biz.ai_conversations —— AI 对话记录
CREATE TABLE IF NOT EXISTS biz.ai_conversations (
    id              BIGSERIAL    PRIMARY KEY,
    user_id         VARCHAR(50)  NOT NULL,
    nickname        VARCHAR(100) NOT NULL DEFAULT '',
    app_id          VARCHAR(30)  NOT NULL,
    site_id         BIGINT       NOT NULL,
    source_page     VARCHAR(100),
    source_context  JSONB,
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE biz.ai_conversations IS 'AI 对话记录：每次 AI 调用（用户主动或系统自动）创建一条';
COMMENT ON COLUMN biz.ai_conversations.app_id IS '应用标识：app1_chat / app2_finance / app3_clue / app4_analysis / app5_tactics / app6_note / app7_customer / app8_consolidation';
COMMENT ON COLUMN biz.ai_conversations.user_id IS '用户 ID，系统自动调用时为 system';

CREATE INDEX IF NOT EXISTS idx_ai_conv_user_site ON biz.ai_conversations (user_id, site_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_ai_conv_app_site ON biz.ai_conversations (app_id, site_id, created_at DESC);

-- 2. biz.ai_messages —— AI 消息记录
CREATE TABLE IF NOT EXISTS biz.ai_messages (
    id              BIGSERIAL    PRIMARY KEY,
    conversation_id BIGINT       NOT NULL REFERENCES biz.ai_conversations(id) ON DELETE CASCADE,
    role            VARCHAR(10)  NOT NULL
        CONSTRAINT chk_ai_msg_role CHECK (role IN ('user', 'assistant', 'system')),
    content         TEXT         NOT NULL,
    tokens_used     INTEGER,
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE biz.ai_messages IS 'AI 消息记录：对话中的每条消息（输入/输出/系统）';

CREATE INDEX IF NOT EXISTS idx_ai_msg_conv ON biz.ai_messages (conversation_id, created_at);

-- 3. biz.ai_cache —— AI 应用缓存
CREATE TABLE IF NOT EXISTS biz.ai_cache (
    id              BIGSERIAL    PRIMARY KEY,
    cache_type      VARCHAR(30)  NOT NULL
        CONSTRAINT chk_ai_cache_type CHECK (
            cache_type IN (
                'app2_finance', 'app3_clue', 'app4_analysis',
                'app5_tactics', 'app6_note_analysis',
                'app7_customer_analysis', 'app8_clue_consolidated'
            )
        ),
    site_id         BIGINT       NOT NULL,
    target_id       VARCHAR(100) NOT NULL,
    result_json     JSONB        NOT NULL,
    score           INTEGER,
    triggered_by    VARCHAR(100),
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    expires_at      TIMESTAMPTZ
);

COMMENT ON TABLE biz.ai_cache IS 'AI 应用缓存：各应用的结构化输出结果';
COMMENT ON COLUMN biz.ai_cache.target_id IS '目标 ID：App2=时间维度编码 / App3,6,7,8=member_id / App4,5={assistant_id}_{member_id}';
COMMENT ON COLUMN biz.ai_cache.score IS '评分：仅应用 6 使用（1-10 分）';

CREATE INDEX IF NOT EXISTS idx_ai_cache_lookup ON biz.ai_cache (cache_type, site_id, target_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_ai_cache_cleanup ON biz.ai_cache (cache_type, site_id, target_id, created_at);
