SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 三方支付是支付管理下的功能；内购配置也归到支付管理，不再挂在 APP 配置下。
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
  ('三方支付查看', 'payment-third-party:view', 'menu', '', @now_ms, @now_ms),
  ('三方支付更新', 'payment-third-party: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, '三方支付', 'payment-third-party', '/payment/third-party', 'wallet', 'payment-third-party:view', 69, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'payment'
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 = 'payment'
SET child.parent_id = parent.id,
    child.path = '/payment/recharge-products',
    child.sort = 70,
    child.visible = TRUE,
    child.updated_at_ms = @now_ms
WHERE child.code = 'payment-recharge-products';

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 ('payment-third-party:view', 'payment-third-party: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 = 'payment-third-party:view';
