SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 补齐活动管理下由既有 bootstrap seed 提供、但历史 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
  ('用户榜单查看', 'user-leaderboard:view', 'menu', '', @now_ms, @now_ms),
  ('红包配置查看', 'red-packet:view', 'menu', '', @now_ms, @now_ms),
  ('红包配置更新', 'red-packet:update', '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, '用户榜单', 'user-leaderboard', '/activities/user-leaderboards', 'leaderboard', 'user-leaderboard:view', 74, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'activities'
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;

INSERT INTO admin_menus (parent_id, title, code, path, icon, permission_code, sort, visible, created_at_ms, updated_at_ms)
SELECT parent.id, '红包配置', 'red-packet', '/activities/red-packets', 'redeem', 'red-packet:view', 76, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'activities'
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;

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 = 'platform-admin'
  AND admin_permission.code IN ('user-leaderboard:view', 'red-packet:view', 'red-packet:update');

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 = 'ops-admin'
  AND admin_permission.code IN ('user-leaderboard:view', 'red-packet:view', 'red-packet:update');

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 IN ('user-leaderboard:view', 'red-packet:view');
