-- Webconsole rocket configuration menu and API permissions.
-- Adds the page under 运营管理/数据配置 and grants it to existing data-config roles.

SET NAMES utf8mb4;

INSERT INTO sys_resource (id, resource_name, mapping, method, auth_type, perm, update_time)
VALUES
  (
    'rocket:config:list',
    '查询火箭配置',
    '/admin/rocket/config/list',
    'GET',
    3,
    'rocket:config:list',
    NOW()
  ),
  (
    'rocket:config:update',
    '更新火箭配置',
    '/admin/rocket/config/update',
    'POST',
    3,
    'rocket:config:update',
    NOW()
  )
ON DUPLICATE KEY UPDATE
  resource_name = VALUES(resource_name),
  mapping = VALUES(mapping),
  method = VALUES(method),
  auth_type = VALUES(auth_type),
  perm = VALUES(perm),
  update_time = NOW();

INSERT INTO sys_menu (
  parent_id,
  menu_name,
  path,
  router,
  menu_type,
  icon,
  alias,
  sort,
  status,
  create_user,
  update_user,
  create_time,
  update_time
)
SELECT
  parent.id,
  '火箭配置',
  'rocket/config/index',
  'rocket/config',
  2,
  'gift',
  'rocket:config',
  850,
  0,
  '0',
  '0',
  NOW(),
  NOW()
FROM sys_menu parent
LEFT JOIN sys_menu existing ON existing.alias = 'rocket:config'
WHERE (parent.alias = 'data:conf' OR parent.menu_name = '数据配置')
  AND parent.menu_type = 1
  AND existing.id IS NULL
LIMIT 1;

-- 关键逻辑：重复执行时同步菜单字段，并始终归属当前的数据配置目录。
UPDATE sys_menu rocket_menu
JOIN (
  SELECT id
  FROM sys_menu
  WHERE (alias = 'data:conf' OR menu_name = '数据配置')
    AND menu_type = 1
  LIMIT 1
) parent ON 1 = 1
SET
  rocket_menu.parent_id = parent.id,
  rocket_menu.menu_name = '火箭配置',
  rocket_menu.path = 'rocket/config/index',
  rocket_menu.router = 'rocket/config',
  rocket_menu.menu_type = 2,
  rocket_menu.icon = 'gift',
  rocket_menu.sort = 850,
  rocket_menu.status = 0,
  rocket_menu.update_user = '0',
  rocket_menu.update_time = NOW()
WHERE rocket_menu.alias = 'rocket:config';

INSERT INTO sys_menu_resource (menu_id, resource_id)
SELECT menu.id, resource.id
FROM sys_menu menu
JOIN sys_resource resource
  ON resource.id IN ('rocket:config:list', 'rocket:config:update')
LEFT JOIN sys_menu_resource existing
  ON existing.menu_id = menu.id
  AND existing.resource_id = resource.id
WHERE menu.alias = 'rocket:config'
  AND existing.id IS NULL;

-- 沿用数据配置目录的现有角色授权，避免将火箭配置开放给无关角色。
INSERT INTO sys_role_menu (role_id, menu_id)
SELECT DISTINCT source_role.role_id, rocket_menu.id
FROM sys_role_menu source_role
JOIN sys_menu source_menu ON source_menu.id = source_role.menu_id
JOIN sys_menu rocket_menu ON rocket_menu.alias = 'rocket:config'
LEFT JOIN sys_role_menu existing
  ON existing.role_id = source_role.role_id
  AND existing.menu_id = rocket_menu.id
WHERE source_menu.alias = 'data:conf'
  AND existing.id IS NULL;
