SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 活动模版配置事实由 activity-service 持有；后台仅提供 RBAC、审计和 HTTP 到 gRPC 的协议适配。
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
  ('活动模版查看', 'activity-template:view', 'menu', '', @now_ms, @now_ms),
  ('活动模版创建', 'activity-template:create', 'button', '', @now_ms, @now_ms),
  ('活动模版更新', 'activity-template:update', 'button', '', @now_ms, @now_ms),
  ('活动模版发布', 'activity-template:publish', 'button', '', @now_ms, @now_ms),
  ('活动模版删除', 'activity-template:delete', 'button', '', @now_ms, @now_ms),
  ('活动模版数据', 'activity-template:data', 'button', '查看活动聚合数据、榜单与奖励发放记录', @now_ms, @now_ms),
  ('活动模版导出', 'activity-template:export', 'button', '导出受时间范围和维度上限约束的活动聚合数据', @now_ms, @now_ms),
  ('活动模版重试', 'activity-template:retry', 'button', '重试失败的活动榜单奖励发放任务', @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  kind = VALUES(kind),
  description = VALUES(description),
  updated_at_ms = @now_ms;

-- parent code 保持 activities 兼容既有路径和角色，但展示名按本期产品信息架构统一为“运营活动”。
INSERT INTO admin_menus (parent_id, title, code, path, icon, permission_code, sort, visible, created_at_ms, updated_at_ms) VALUES
  (NULL, '运营活动', 'activities', '', 'campaign', '', 90, TRUE, @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  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, '活动模版', 'activity-template', '/activities/templates', 'campaign', 'activity-template:view', 68, 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 IN ('platform-admin', 'ops-admin', 'product-lead')
  AND admin_permission.code IN (
    'activity-template:view', 'activity-template:create', 'activity-template:update', 'activity-template:publish',
    'activity-template:delete', 'activity-template:data', 'activity-template:export', 'activity-template:retry'
  );

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 ('operations-specialist', 'product-specialist', 'auditor', 'readonly')
  AND admin_permission.code IN ('activity-template:view', 'activity-template:data');
