SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CP排行活动对应 H5 的 cp-weekly-rank 活动读接口；后台只维护启停、Top 奖励资源组和查看发奖事实。
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
  ('CP 排行活动查看', 'cp-weekly-rank:view', 'menu', '', @now_ms, @now_ms),
  ('CP 排行活动更新', 'cp-weekly-rank: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, 'CP排行活动', 'cp-weekly-rank', '/activities/cp-weekly-rank', 'leaderboard', 'cp-weekly-rank:view', 77, 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;

UPDATE admin_menus
SET sort = 78, updated_at_ms = @now_ms
WHERE code = 'vip-config';

UPDATE admin_menus
SET sort = 79, updated_at_ms = @now_ms
WHERE code = 'weekly-star';

UPDATE admin_menus
SET sort = 80, updated_at_ms = @now_ms
WHERE code = 'agency-opening';

UPDATE admin_menus
SET sort = 81, updated_at_ms = @now_ms
WHERE code = 'wheel';

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 ('cp-weekly-rank:view', 'cp-weekly-rank: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 = 'cp-weekly-rank:view';
