-- ============================================================
-- M7-10: ChatScope 旧数据回填
-- 将 M-CHAT 里程碑前创建的旧会话补全 scope 字段
-- 可重复执行（idempotent）：只更新 scopeId IS NULL 的记录
-- ============================================================

-- 1. 回填 scope 字段
UPDATE "ChatSession"
SET
  "scopeType" = 'knowledge_base',
  "scopeId" = "knowledgeBaseId",
  "parentKnowledgeBaseId" = "knowledgeBaseId",
  "createdFrom" = 'legacy_migration',
  "lastMessageAt" = COALESCE("lastMessageAt", "updatedAt")
WHERE "scopeId" IS NULL
  AND "scopeType" = 'knowledge_base';  -- 默认值

-- 2. 验证
-- SELECT COUNT(*) AS backfilled_count FROM "ChatSession" WHERE "createdFrom" = 'legacy_migration';
-- SELECT id, title, "scopeType", "scopeId", "parentKnowledgeBaseId", "createdFrom" FROM "ChatSession" WHERE "scopeId" IS NULL;
