SET @sys_user_switch_account_key_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'sys_user'
      AND COLUMN_NAME = 'tenant_switch_account_key'
);

SET @sys_user_switch_account_key_sql = IF(
    @sys_user_switch_account_key_exists = 0,
    'ALTER TABLE sys_user ADD COLUMN tenant_switch_account_key VARCHAR(64) NULL AFTER password_hash',
    'SELECT 1'
);
PREPARE stmt_sys_user_switch_account_key FROM @sys_user_switch_account_key_sql;
EXECUTE stmt_sys_user_switch_account_key;
DEALLOCATE PREPARE stmt_sys_user_switch_account_key;

SET @sys_user_switch_account_key_idx_exists = (
    SELECT COUNT(1)
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'sys_user'
      AND INDEX_NAME = 'idx_sys_user_switch_account_key'
);

SET @sys_user_switch_account_key_idx_sql = IF(
    @sys_user_switch_account_key_idx_exists = 0,
    'ALTER TABLE sys_user ADD KEY idx_sys_user_switch_account_key (tenant_switch_account_key, status, is_deleted)',
    'SELECT 1'
);
PREPARE stmt_sys_user_switch_account_key_idx FROM @sys_user_switch_account_key_idx_sql;
EXECUTE stmt_sys_user_switch_account_key_idx;
DEALLOCATE PREPARE stmt_sys_user_switch_account_key_idx;

UPDATE sys_user
SET tenant_switch_account_key = CONCAT('acct_', UPPER(MD5(CONCAT(IFNULL(phone, ''), '|', IFNULL(password_hash, '')))))
WHERE tenant_switch_account_key IS NULL OR tenant_switch_account_key = '';
