SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 送礼记录是 wallet-service 已成功送礼交易的只读审计入口；本迁移只写后台权限、菜单和固定岗位授权。
-- 迁移查询都命中 admin_permissions/admin_menus/admin_roles 的唯一索引，不扫描钱包或用户业务表。
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
  ('送礼记录查看', 'gift-record:view', 'menu', '允许查看真实用户房间及私聊送礼记录', @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, '送礼记录', 'operation-gift-records', '/operations/gift-records', 'gift', 'gift-record:view', 67, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'operations'
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;

-- 固定岗位中原本拥有运营只读模块的角色同步获得送礼记录；平台管理员也显式补齐，兼容未执行 bootstrap 的存量库。
INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT role.id, permission.id
FROM admin_roles role
JOIN admin_permissions permission ON permission.code = 'gift-record:view'
WHERE role.code IN (
  'platform-admin', 'ops-admin', 'operations-specialist',
  'product-lead', 'product-specialist', 'auditor', 'readonly'
);
