-- 房间白名单允许指定用户在 App 房间列表绕过 visible_region_id 过滤；本迁移只写后台菜单和权限事实。
SET @now_ms := UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000;

INSERT INTO admin_permissions (name, code, kind, description, created_at_ms, updated_at_ms) VALUES
  ('房间白名单查看', 'room-whitelist:view', 'menu', '允许查看房间白名单配置', @now_ms, @now_ms),
  ('房间白名单更新', 'room-whitelist:update', 'button', '允许更新房间白名单配置', @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  kind = VALUES(kind),
  description = VALUES(description),
  updated_at_ms = VALUES(updated_at_ms);

INSERT INTO admin_menus (parent_id, title, code, path, icon, permission_code, sort, visible, created_at_ms, updated_at_ms)
SELECT parent.id, '房间白名单', 'room-whitelist', '/rooms/whitelist', 'shield', 'room-whitelist:view', 68, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'rooms'
ON DUPLICATE KEY UPDATE
  parent_id = VALUES(parent_id),
  title = VALUES(title),
  path = VALUES(path),
  icon = VALUES(icon),
  permission_code = VALUES(permission_code),
  sort = VALUES(sort),
  visible = VALUES(visible),
  updated_at_ms = VALUES(updated_at_ms);

UPDATE admin_menus
SET sort = 69, updated_at_ms = @now_ms
WHERE code = 'room-robots' AND sort < 69;

INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM admin_roles r
JOIN admin_permissions p ON p.code IN ('room-whitelist:view', 'room-whitelist:update')
WHERE r.code IN ('platform-admin', 'ops-admin');

INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT r.id, p.id
FROM admin_roles r
JOIN admin_permissions p ON p.code = 'room-whitelist:view'
WHERE r.code IN ('auditor', 'readonly');
