SET NAMES utf8mb4;

SET @operate_manager_id := (
  SELECT id
  FROM sys_menu
  WHERE alias = 'OperateManager'
  LIMIT 1
);

INSERT INTO sys_menu (
  id,
  parent_id,
  menu_name,
  path,
  menu_type,
  icon,
  create_user,
  update_user,
  sort,
  status,
  router,
  alias
)
SELECT
  menu_id.next_id,
  @operate_manager_id,
  '区域飘屏',
  'operate/region-broadcast',
  2,
  'lucide:radio-tower',
  '0',
  '0',
  18,
  0,
  'region-broadcast',
  'OperateRegionBroadcast'
FROM (
  SELECT COALESCE(MAX(id), 1700000000) + 1 AS next_id
  FROM sys_menu
) AS menu_id
WHERE @operate_manager_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM sys_menu WHERE alias = 'OperateRegionBroadcast'
  );

UPDATE sys_menu
SET
  parent_id = @operate_manager_id,
  menu_name = '区域飘屏',
  path = 'operate/region-broadcast',
  menu_type = 2,
  icon = 'lucide:radio-tower',
  update_user = '0',
  sort = 18,
  status = 0,
  router = 'region-broadcast'
WHERE alias = 'OperateRegionBroadcast'
  AND @operate_manager_id IS NOT NULL;

INSERT INTO sys_role_menu (role_id, menu_id)
SELECT DISTINCT
  role_menu.role_id,
  target_menu.id
FROM sys_role_menu AS role_menu
JOIN sys_menu AS source_menu
  ON source_menu.id = role_menu.menu_id
  AND source_menu.alias = 'OperateManager'
JOIN sys_menu AS target_menu
  ON target_menu.alias = 'OperateRegionBroadcast'
WHERE NOT EXISTS (
  SELECT 1
  FROM sys_role_menu AS existing_role_menu
  WHERE existing_role_menu.role_id = role_menu.role_id
    AND existing_role_menu.menu_id = target_menu.id
);
