SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

SET @now_ms = CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED);

CREATE TABLE IF NOT EXISTS admin_user_money_scopes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  user_id BIGINT UNSIGNED NOT NULL COMMENT '后台用户 ID',
  app_code VARCHAR(32) NOT NULL COMMENT '应用编码',
  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '区域 ID，0 表示整个 app',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  UNIQUE KEY uk_admin_user_money_scope (user_id, app_code, region_id),
  KEY idx_admin_user_money_scopes_user (user_id),
  KEY idx_admin_user_money_scopes_app_region (app_code, region_id),
  CONSTRAINT fk_admin_user_money_scopes_user FOREIGN KEY (user_id) REFERENCES admin_users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='后台用户财务系统 app/区域范围';

CREATE TABLE IF NOT EXISTS admin_temporary_payment_link_owners (
  app_code VARCHAR(32) NOT NULL COMMENT '应用编码',
  order_id VARCHAR(96) NOT NULL COMMENT 'wallet external_recharge_orders.order_id',
  admin_user_id BIGINT UNSIGNED NOT NULL COMMENT '创建支付链接的后台用户 ID',
  region_id BIGINT NOT NULL COMMENT '支付链接归属区域 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  PRIMARY KEY (app_code, order_id),
  KEY idx_admin_temporary_payment_link_owners_user (admin_user_id, created_at_ms),
  KEY idx_admin_temporary_payment_link_owners_region (app_code, region_id, created_at_ms),
  CONSTRAINT fk_admin_temporary_payment_link_owners_user FOREIGN KEY (admin_user_id) REFERENCES admin_users(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='临时支付链接后台归属';

INSERT INTO admin_permissions (name, code, kind, description, created_at_ms, updated_at_ms) VALUES
  ('财务支付链接创建', 'money:payment-link:create', '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 ('money:view', 'money:payment-link:create');
