SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 房间置顶是房间管理里的运营入口；生产环境关闭 bootstrap 时，只能依赖 migration 补齐菜单和权限事实。
SET @now_ms = CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

INSERT INTO admin_permissions (name, code, kind, description, created_at_ms, updated_at_ms) VALUES
  ('房间置顶查看', 'room-pin:view', 'menu', '允许查看房间置顶列表', @now_ms, @now_ms),
  ('房间置顶创建', 'room-pin:create', 'button', '允许新增或恢复房间置顶', @now_ms, @now_ms),
  ('房间置顶取消', 'room-pin:cancel', 'button', '允许取消房间置顶', @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  kind = VALUES(kind),
  description = VALUES(description),
  updated_at_ms = @now_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-pins', '/rooms/pins', 'push_pin', 'room-pin:view', 66, 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 = @now_ms;

-- 置顶入口排在房间配置、白名单和机器人房间前面；显式排序避免多次修复或历史状态不同造成排序漂移。
UPDATE admin_menus
SET sort = CASE code
    WHEN 'room-config' THEN 67
    WHEN 'room-whitelist' THEN 68
    WHEN 'room-robots' THEN 69
    ELSE sort
  END,
  updated_at_ms = @now_ms
WHERE code IN ('room-config', 'room-whitelist', 'room-robots');

-- 平台和运营角色可以执行置顶变更；只读和审计角色只能看到列表，避免误给写权限。
INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT admin_role.id, admin_permission.id
FROM admin_roles admin_role
JOIN admin_permissions admin_permission
WHERE admin_role.code IN ('platform-admin', 'ops-admin')
  AND admin_permission.code IN ('room-pin:view', 'room-pin:create', 'room-pin:cancel');

INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT admin_role.id, admin_permission.id
FROM admin_roles admin_role
JOIN admin_permissions admin_permission
WHERE admin_role.code IN ('auditor', 'readonly')
  AND admin_permission.code = 'room-pin:view';
