SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- P1: 非 AI 核心模块并发安全增强（系统模块/数据关系模块）
-- 说明：本脚本为一次性增量执行脚本。

-- 1) 关系表去重（按业务复合键保留最小 id）
DELETE t1
FROM tb_sys_account_position t1
         INNER JOIN tb_sys_account_position t2
                    ON t1.account_id = t2.account_id
                        AND t1.position_id = t2.position_id
                        AND t1.id > t2.id;

DELETE t1
FROM tb_sys_account_role t1
         INNER JOIN tb_sys_account_role t2
                    ON t1.account_id = t2.account_id
                        AND t1.role_id = t2.role_id
                        AND t1.id > t2.id;

DELETE t1
FROM tb_sys_role_menu t1
         INNER JOIN tb_sys_role_menu t2
                    ON t1.role_id = t2.role_id
                        AND t1.menu_id = t2.menu_id
                        AND t1.id > t2.id;

DELETE t1
FROM tb_sys_role_dept t1
         INNER JOIN tb_sys_role_dept t2
                    ON t1.role_id = t2.role_id
                        AND t1.dept_id = t2.dept_id
                        AND t1.id > t2.id;

DELETE t1
FROM tb_sys_api_key_resource_mapping t1
         INNER JOIN tb_sys_api_key_resource_mapping t2
                    ON t1.api_key_id = t2.api_key_id
                        AND t1.api_key_resource_id = t2.api_key_resource_id
                        AND t1.id > t2.id;

DELETE t1
FROM tb_sys_api_key t1
         INNER JOIN tb_sys_api_key t2
                    ON t1.api_key = t2.api_key
                        AND t1.id > t2.id
WHERE t1.api_key IS NOT NULL;

-- 2) sys_option 去重（无主键表，采用临时表重建）
DROP TABLE IF EXISTS tb_sys_option_tmp;
CREATE TABLE tb_sys_option_tmp LIKE tb_sys_option;
ALTER TABLE tb_sys_option_tmp DROP INDEX uni_key;
INSERT INTO tb_sys_option_tmp (tenant_id, `key`, `value`)
SELECT tenant_id, `key`, ANY_VALUE(`value`)
FROM tb_sys_option
GROUP BY tenant_id, `key`;
DELETE
FROM tb_sys_option;
INSERT INTO tb_sys_option (tenant_id, `key`, `value`)
SELECT tenant_id, `key`, `value`
FROM tb_sys_option_tmp;
DROP TABLE IF EXISTS tb_sys_option_tmp;

-- 3) 增加唯一约束（并发写兜底）
ALTER TABLE tb_sys_account_position
    ADD UNIQUE INDEX uni_account_position (account_id, position_id);

ALTER TABLE tb_sys_account_role
    ADD UNIQUE INDEX uni_account_role (account_id, role_id);

ALTER TABLE tb_sys_role_menu
    ADD UNIQUE INDEX uni_role_menu (role_id, menu_id);

ALTER TABLE tb_sys_role_dept
    ADD UNIQUE INDEX uni_role_dept (role_id, dept_id);

ALTER TABLE tb_sys_api_key_resource_mapping
    ADD UNIQUE INDEX uni_api_key_resource (api_key_id, api_key_resource_id);

ALTER TABLE tb_sys_api_key
    ADD UNIQUE INDEX uni_api_key (api_key);

ALTER TABLE tb_sys_option
    DROP INDEX uni_key,
    ADD UNIQUE INDEX uni_key (tenant_id, `key`);

SET FOREIGN_KEY_CHECKS = 1;
