SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_user;

-- 登录版本画像必须记录每次真实认证携带的客户端版本，而不是复用用户注册时的一次性版本快照。
-- 所有 DDL 都先检查 information_schema，使已通过 initdb 创建新字段的环境也可以安全重复执行。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'login_audit' AND COLUMN_NAME = 'app_version') = 0,
  'ALTER TABLE login_audit ADD COLUMN app_version VARCHAR(64) NOT NULL DEFAULT '''' COMMENT ''本次认证客户端版本'' AFTER platform',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'login_audit' AND COLUMN_NAME = 'build_number') = 0,
  'ALTER TABLE login_audit ADD COLUMN build_number VARCHAR(64) NOT NULL DEFAULT '''' COMMENT ''本次认证客户端构建号'' AFTER app_version',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'login_audit' AND INDEX_NAME = 'idx_login_audit_latest_success') = 0,
  'ALTER TABLE login_audit ADD INDEX idx_login_audit_latest_success (app_code, user_id, result, blocked, login_type, created_at_ms, id)',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
