SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 财务系统已从旧 money 子系统拆成“申请发起”和“财务审核”两类权限；操作项也独立成按钮权限，方便后台角色配置精确授权。
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-temporary-link:create', 'button', '允许创建三方临时支付链接', @now_ms, @now_ms),
  ('财务范围查看', 'finance:view', 'menu', '允许读取财务系统 APP 和区域范围', @now_ms, @now_ms),
  ('财务申请发起', 'finance-application:create', 'button', '允许发起财务操作申请', @now_ms, @now_ms),
  ('财务申请审核', 'finance-application:audit', 'button', '允许查看并审核财务操作申请', @now_ms, @now_ms),
  ('财务增加用户金币', 'finance-operation:user-coin-credit', 'button', '允许申请增加用户金币', @now_ms, @now_ms),
  ('财务减少用户金币', 'finance-operation:user-coin-debit', 'button', '允许申请减少用户金币', @now_ms, @now_ms),
  ('财务增加用户钱包', 'finance-operation:user-wallet-credit', 'button', '允许申请增加 host/agency/bd 钱包', @now_ms, @now_ms),
  ('财务扣减用户钱包', 'finance-operation:user-wallet-debit', 'button', '允许申请扣减 host/agency/bd 钱包', @now_ms, @now_ms),
  ('财务增加币商金币', 'finance-operation:coin-seller-coin-credit', 'button', '允许申请增加币商金币', @now_ms, @now_ms),
  ('财务减少币商金币', 'finance-operation:coin-seller-coin-debit', 'button', '允许申请减少币商金币', @now_ms, @now_ms)
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  kind = VALUES(kind),
  description = VALUES(description),
  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 = 'platform-admin'
  AND admin_permission.code IN (
    'payment-temporary-link:create',
    'finance:view',
    'finance-application:create',
    'finance-application:audit',
    'finance-operation:user-coin-credit',
    'finance-operation:user-coin-debit',
    'finance-operation:user-wallet-credit',
    'finance-operation:user-wallet-debit',
    'finance-operation:coin-seller-coin-credit',
    'finance-operation:coin-seller-coin-debit'
  );

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 = 'ops-admin'
  AND admin_permission.code IN (
    'payment-temporary-link:create',
    'finance-application:create',
    'finance-operation:user-coin-credit',
    'finance-operation:user-coin-debit',
    'finance-operation:user-wallet-credit',
    'finance-operation:user-wallet-debit',
    'finance-operation:coin-seller-coin-credit',
    'finance-operation:coin-seller-coin-debit'
  );

DELETE admin_role_permissions
FROM admin_role_permissions
JOIN admin_permissions ON admin_permissions.id = admin_role_permissions.permission_id
WHERE admin_permissions.code IN ('money:view', 'money:payment-link:create');

DELETE FROM admin_permissions
WHERE code IN ('money:view', 'money:payment-link:create');
