CREATE TABLE IF NOT EXISTS auth_risk_configs (
  app_code VARCHAR(32) NOT NULL PRIMARY KEY COMMENT '应用编码，用于多租户隔离',
  max_accounts_per_device INT NOT NULL DEFAULT 1 COMMENT '单设备最大注册账号数',
  updated_by_admin_id BIGINT NOT NULL DEFAULT 0 COMMENT '最近修改后台管理员 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='认证注册风控配置';

INSERT INTO auth_risk_configs (app_code, max_accounts_per_device, updated_by_admin_id, created_at_ms, updated_at_ms)
SELECT app_code, 1, 0, CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED), CAST(UNIX_TIMESTAMP(UTC_TIMESTAMP(3)) * 1000 AS UNSIGNED)
FROM apps
ON DUPLICATE KEY UPDATE
  max_accounts_per_device = max_accounts_per_device;

SET @drop_unique_register_device_id := (
  SELECT IF(
    COUNT(*) > 0,
    'ALTER TABLE users DROP INDEX uk_users_register_device_id',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'users'
    AND INDEX_NAME = 'uk_users_register_device_id'
    AND NON_UNIQUE = 0
);

PREPARE stmt FROM @drop_unique_register_device_id;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_register_device_id_index := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE users ADD INDEX idx_users_register_device_id (app_code, register_device_id)',
    'SELECT 1'
  )
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'users'
    AND INDEX_NAME = 'idx_users_register_device_id'
);

PREPARE stmt FROM @add_register_device_id_index;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
