SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- P1: 多机部署并发安全增强（唯一约束 + 去重）
-- 注意：本脚本为增量脚本，建议仅执行一次。

-- 1) 清理 bot-knowledge 重复绑定
DELETE t1
FROM tb_bot_document_collection t1
         INNER JOIN tb_bot_document_collection t2
                    ON t1.bot_id <=> t2.bot_id
                        AND t1.document_collection_id <=> t2.document_collection_id
                        AND t1.id > t2.id;

-- 2) 清理 bot-workflow 重复绑定
DELETE t1
FROM tb_bot_workflow t1
         INNER JOIN tb_bot_workflow t2
                    ON t1.bot_id <=> t2.bot_id
                        AND t1.workflow_id <=> t2.workflow_id
                        AND t1.id > t2.id;

-- 3) 清理 bot-plugin 重复绑定
DELETE t1
FROM tb_bot_plugin t1
         INNER JOIN tb_bot_plugin t2
                    ON t1.bot_id <=> t2.bot_id
                        AND t1.plugin_item_id <=> t2.plugin_item_id
                        AND t1.id > t2.id;

-- 4) 清理 bot-mcp 重复绑定
DELETE t1
FROM tb_bot_mcp t1
         INNER JOIN tb_bot_mcp t2
                    ON t1.bot_id <=> t2.bot_id
                        AND t1.mcp_id <=> t2.mcp_id
                        AND t1.mcp_tool_name <=> t2.mcp_tool_name
                        AND t1.id > t2.id;

-- 5) 清理最近使用重复记录
DELETE t1
FROM tb_bot_recently_used t1
         INNER JOIN tb_bot_recently_used t2
                    ON t1.created_by = t2.created_by
                        AND t1.bot_id = t2.bot_id
                        AND t1.id > t2.id;

-- 增加唯一索引（并发写最终一致性兜底）
ALTER TABLE tb_bot_document_collection
    ADD UNIQUE INDEX uni_bot_document_collection (bot_id, document_collection_id);

ALTER TABLE tb_bot_workflow
    ADD UNIQUE INDEX uni_bot_workflow (bot_id, workflow_id);

ALTER TABLE tb_bot_plugin
    ADD UNIQUE INDEX uni_bot_plugin (bot_id, plugin_item_id);

ALTER TABLE tb_bot_mcp
    ADD UNIQUE INDEX uni_bot_mcp (bot_id, mcp_id, mcp_tool_name);

ALTER TABLE tb_bot_recently_used
    ADD UNIQUE INDEX uni_bot_recently_used (created_by, bot_id);

SET FOREIGN_KEY_CHECKS = 1;
