SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 两列都是短 VARCHAR；线上使用 INPLACE/LOCK=NONE，避免跨 App 接入时阻塞现有 Lalu 提现写入。
SET @source_system_exists = (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_user_withdrawal_applications'
    AND COLUMN_NAME = 'source_system'
);

SET @source_system_ddl = IF(
  @source_system_exists = 0,
  'ALTER TABLE admin_user_withdrawal_applications ADD COLUMN source_system VARCHAR(32) NOT NULL DEFAULT ''hyapp_wallet'' AFTER app_code, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);

PREPARE stmt FROM @source_system_ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @source_application_id_exists = (
  SELECT COUNT(*)
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_user_withdrawal_applications'
    AND COLUMN_NAME = 'source_application_id'
);

SET @source_application_id_ddl = IF(
  @source_application_id_exists = 0,
  'ALTER TABLE admin_user_withdrawal_applications ADD COLUMN source_application_id VARCHAR(128) NOT NULL DEFAULT '''' AFTER source_system, ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);

PREPARE stmt FROM @source_application_id_ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 存量 Lalu 单使用已经唯一的 freeze_command_id 作为来源单号，确保新增唯一索引不会发生空值碰撞。
UPDATE admin_user_withdrawal_applications
SET source_system = 'hyapp_wallet',
    source_application_id = freeze_command_id
WHERE source_application_id = '';

SET @source_index_exists = (
  SELECT COUNT(*)
  FROM information_schema.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'admin_user_withdrawal_applications'
    AND INDEX_NAME = 'uk_admin_withdrawal_source_application'
);

-- 唯一索引同时承担来源重试的幂等查找；列选择性高，不增加列表查询扫描成本。
SET @source_index_ddl = IF(
  @source_index_exists = 0,
  'ALTER TABLE admin_user_withdrawal_applications ADD UNIQUE KEY uk_admin_withdrawal_source_application (app_code, source_system, source_application_id), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);

PREPARE stmt FROM @source_index_ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
