-- 验证重复消息修复效果的SQL脚本

-- 1. 查看最新的消息记录（修复后应该只有一条用户消息）
SELECT 
    id, 
    conversation_id, 
    content, 
    sender, 
    user_id, 
    user_type, 
    coze_role, 
    create_by, 
    create_time,
    update_time
FROM message 
WHERE create_time > '2025-07-25 16:15:00'  -- 修复后的时间
ORDER BY create_time DESC 
LIMIT 20;

-- 2. 检查是否还有重复的用户消息（修复后应该返回0条记录）
SELECT 
    content, 
    conversation_id,
    sender,
    COUNT(*) as duplicate_count,
    GROUP_CONCAT(id) as message_ids,
    MIN(create_time) as first_time,
    MAX(create_time) as last_time
FROM message 
WHERE sender = 'user'
  AND create_time > '2025-07-25 16:15:00'  -- 修复后的时间
GROUP BY content, conversation_id, sender
HAVING COUNT(*) > 1;

-- 3. 查看特定会话的消息流（验证消息顺序正常）
-- 请将 'YOUR_CONVERSATION_ID' 替换为实际的会话ID
SELECT 
    id,
    content,
    sender,
    user_id,
    user_type,
    create_time,
    CASE 
        WHEN user_id IS NOT NULL AND user_type IS NOT NULL THEN 'WebSocket保存'
        WHEN user_id IS NULL AND create_by != 'system' THEN 'REST API保存'
        ELSE '其他方式保存'
    END as save_method
FROM message 
WHERE conversation_id = 'YOUR_CONVERSATION_ID'
ORDER BY create_time ASC;

-- 4. 统计修复前后的消息数量对比
SELECT 
    DATE(create_time) as date,
    sender,
    COUNT(*) as message_count
FROM message 
WHERE create_time >= '2025-07-25 00:00:00'
GROUP BY DATE(create_time), sender
ORDER BY date DESC, sender;

-- 5. 查找可能的重复消息模式
SELECT 
    content,
    sender,
    COUNT(*) as count,
    GROUP_CONCAT(DISTINCT user_id) as user_ids,
    GROUP_CONCAT(DISTINCT create_by) as create_bys
FROM message 
WHERE create_time > '2025-07-25 16:00:00'
GROUP BY content, sender
HAVING COUNT(*) > 1;
