SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 币商流水只读 wallet-service 币商专用金币分录；本迁移只写后台权限、菜单和默认角色授权。
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
  ('币商流水查看', 'coin-seller-ledger: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) VALUES
  (NULL, '运营管理', 'operations', '', 'operations', '', 68, 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, '币商流水', 'operation-coin-seller-ledger', '/operations/coin-seller-ledger', 'receipt', 'coin-seller-ledger:view', 69, 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;

UPDATE admin_menus child
JOIN admin_menus parent ON parent.code = 'operations' AND child.parent_id = parent.id
SET child.sort = CASE child.code
  WHEN 'operation-coin-adjustment' THEN 70
  WHEN 'lucky-gift' THEN 71
  WHEN 'operation-reports' THEN 72
  WHEN 'operation-gift-diamond' THEN 73
  ELSE child.sort
END,
child.updated_at_ms = @now_ms
WHERE child.code IN ('operation-coin-adjustment', 'lucky-gift', 'operation-reports', 'operation-gift-diamond');

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', 'auditor', 'readonly')
  AND admin_permission.code = 'coin-seller-ledger:view';
