-- =============================================================================
-- 迁移：扩展 biz.ai_conversations 和 biz.ai_messages 支持 CHAT 模块
-- 日期：2026-03-20
-- 关联 SPEC：rns1-chat-integration（RNS1.4 CHAT 对齐与联调收尾）
-- 需求：R2.3, R3.8, R3.10, R4.3, R7.5
-- 说明：
--   1. ai_conversations 新增 context_type/context_id（多入口对话复用）、
--      title/last_message/last_message_at（历史列表展示与排序）
--   2. ai_messages 新增 reference_card（引用卡片 JSON）
--   3. 两个索引：上下文对话查找 + 历史列表排序
-- =============================================================================

-- ---------------------------------------------------------------------------
-- 1. 扩展 ai_conversations：新增 5 个字段
-- ---------------------------------------------------------------------------
ALTER TABLE biz.ai_conversations
    ADD COLUMN IF NOT EXISTS context_type    varchar(20),
    ADD COLUMN IF NOT EXISTS context_id      varchar(50),
    ADD COLUMN IF NOT EXISTS title           varchar(200),
    ADD COLUMN IF NOT EXISTS last_message    text,
    ADD COLUMN IF NOT EXISTS last_message_at timestamptz;

COMMENT ON COLUMN biz.ai_conversations.context_type
    IS '对话关联上下文类型：task（任务）/ customer（客户）/ coach（助教）/ general（通用）';
COMMENT ON COLUMN biz.ai_conversations.context_id
    IS '关联上下文 ID：task 入口为 taskId，customer 入口为 customerId，coach 入口为 coachId，general 为 NULL';
COMMENT ON COLUMN biz.ai_conversations.title
    IS '对话标题：自定义 > 上下文名称 > 首条消息前20字';
COMMENT ON COLUMN biz.ai_conversations.last_message
    IS '最后一条消息内容摘要（截断至100字）';
COMMENT ON COLUMN biz.ai_conversations.last_message_at
    IS '最后消息时间，用于历史列表排序和对话复用时限判断';

-- ---------------------------------------------------------------------------
-- 2. 扩展 ai_messages：新增 reference_card 字段
-- ---------------------------------------------------------------------------
ALTER TABLE biz.ai_messages
    ADD COLUMN IF NOT EXISTS reference_card jsonb;

COMMENT ON COLUMN biz.ai_messages.reference_card
    IS 'referenceCard JSON：{type, title, summary, data}';

-- ---------------------------------------------------------------------------
-- 3. 索引：上下文对话查找（按 context_type + context_id 查找可复用对话）
-- ---------------------------------------------------------------------------
CREATE INDEX IF NOT EXISTS idx_ai_conv_context
    ON biz.ai_conversations (user_id, site_id, context_type, context_id, last_message_at DESC NULLS LAST)
    WHERE context_type IS NOT NULL;

-- ---------------------------------------------------------------------------
-- 4. 索引：历史列表排序优化（CHAT-1: 按 last_message_at 倒序）
-- ---------------------------------------------------------------------------
CREATE INDEX IF NOT EXISTS idx_ai_conv_last_msg
    ON biz.ai_conversations (user_id, site_id, last_message_at DESC NULLS LAST);

-- =============================================================================
-- 回滚
-- =============================================================================
-- DROP INDEX IF EXISTS biz.idx_ai_conv_context;
-- DROP INDEX IF EXISTS biz.idx_ai_conv_last_msg;
-- ALTER TABLE biz.ai_messages DROP COLUMN IF EXISTS reference_card;
-- ALTER TABLE biz.ai_conversations DROP COLUMN IF EXISTS last_message_at;
-- ALTER TABLE biz.ai_conversations DROP COLUMN IF EXISTS last_message;
-- ALTER TABLE biz.ai_conversations DROP COLUMN IF EXISTS title;
-- ALTER TABLE biz.ai_conversations DROP COLUMN IF EXISTS context_id;
-- ALTER TABLE biz.ai_conversations DROP COLUMN IF EXISTS context_type;

-- =============================================================================
-- 验证
-- =============================================================================
-- 1) ai_conversations 新字段存在性
-- SELECT column_name, data_type, character_maximum_length
-- FROM information_schema.columns
-- WHERE table_schema = 'biz' AND table_name = 'ai_conversations'
--   AND column_name IN ('context_type','context_id','title','last_message','last_message_at');
-- 预期：5 行

-- 2) ai_messages 新字段存在性
-- SELECT column_name, data_type
-- FROM information_schema.columns
-- WHERE table_schema = 'biz' AND table_name = 'ai_messages'
--   AND column_name = 'reference_card';
-- 预期：1 行，jsonb

-- 3) 索引存在性
-- SELECT indexname FROM pg_indexes
-- WHERE schemaname = 'biz' AND tablename = 'ai_conversations'
--   AND indexname IN ('idx_ai_conv_context','idx_ai_conv_last_msg');
-- 预期：2 行
