SET @now_ms := UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000;

INSERT INTO admin_permissions (name, code, kind, description, created_at_ms, updated_at_ms) VALUES
  ('子币商申请查看', 'coin-seller-sub-application:view', 'menu', '允许查看子币商邀请申请列表', @now_ms, @now_ms),
  ('子币商申请审核', 'coin-seller-sub-application:audit', '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, 'Sub Coin Seller 申请列表', 'host-org-coin-seller-sub-applications', '/host/coin-seller-sub-applications', 'receipt', 'coin-seller-sub-application:view', 88, TRUE, @now_ms, @now_ms
FROM admin_menus parent
WHERE parent.code = 'host-org'
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
SET sort = 89, updated_at_ms = @now_ms
WHERE code = 'host-withdrawals' AND sort < 89;

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 ('coin-seller-sub-application:view', 'coin-seller-sub-application:audit');

INSERT IGNORE INTO admin_role_permissions (role_id, permission_id)
SELECT DISTINCT existing.role_id, sub_view.id
FROM admin_role_permissions existing
JOIN admin_permissions coin_view
  ON coin_view.id = existing.permission_id
 AND coin_view.code = 'coin-seller:view'
JOIN admin_permissions sub_view
  ON sub_view.code = 'coin-seller-sub-application:view';

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 = 'coin-seller-sub-application:view';
