-- ============================================
-- 查询白名单 - 后台菜单迁移 SQL
-- 将「模块白名单」替换为「查询白名单」
-- 数据库：ycc
-- 父菜单：产品管理 (48d0e129-a141-4a74-b519-7adc38d22d27)
-- ============================================

-- 1. 软删除旧「模块白名单」菜单
UPDATE `admin_menu`
SET `del_state` = 1, `version` = `version` + 1
WHERE `path` = '/product-manage/whitelist/list' AND `del_state` = 0;

-- 2. 插入「查询白名单」菜单（已存在则跳过）
INSERT INTO `admin_menu` (
  `id`, `pid`, `name`, `path`, `component`, `redirect`, `meta`,
  `status`, `type`, `sort`, `del_state`, `version`
)
SELECT
  'd02e094d-6af8-11f1-bd31-dec53e82fe75',
  '48d0e129-a141-4a74-b519-7adc38d22d27',
  'queryWhitelist',
  '/product-manage/query-whitelist/list',
  '/product-manage/query-whitelist/list',
  NULL,
  JSON_OBJECT('icon', 'lucide:shield-off', 'title', '查询白名单'),
  1,
  1,
  0,
  0,
  0
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM `admin_menu`
  WHERE `path` = '/product-manage/query-whitelist/list' AND `del_state` = 0
);

-- 3. 给「超级管理员」授权新菜单
INSERT INTO `admin_role_menu` (`id`, `role_id`, `menu_id`, `del_state`, `version`)
SELECT
  UUID(),
  '741b7a39-a95d-4b9d-8dc0-84ee664d5fef',
  m.`id`,
  0,
  0
FROM `admin_menu` m
WHERE m.`path` = '/product-manage/query-whitelist/list'
  AND m.`del_state` = 0
  AND NOT EXISTS (
    SELECT 1 FROM `admin_role_menu` rm
    WHERE rm.`role_id` = '741b7a39-a95d-4b9d-8dc0-84ee664d5fef'
      AND rm.`menu_id` = m.`id`
      AND rm.`del_state` = 0
  );

-- 4. 给所有曾拥有旧「模块白名单」权限的角色同步授权
INSERT INTO `admin_role_menu` (`id`, `role_id`, `menu_id`, `del_state`, `version`)
SELECT
  UUID(),
  arm.`role_id`,
  m.`id`,
  0,
  0
FROM `admin_role_menu` arm
JOIN `admin_menu` old_m ON old_m.`path` = '/product-manage/whitelist/list'
JOIN `admin_menu` m ON m.`path` = '/product-manage/query-whitelist/list' AND m.`del_state` = 0
WHERE arm.`menu_id` = old_m.`id`
  AND arm.`del_state` = 0
  AND NOT EXISTS (
    SELECT 1 FROM `admin_role_menu` x
    WHERE x.`role_id` = arm.`role_id`
      AND x.`menu_id` = m.`id`
      AND x.`del_state` = 0
  );

-- 执行后请重新登录管理后台
