#!/usr/bin/env tsx
/**
 * 修复 platform_accounts 表的 created_at 和 updated_at 字段格式
 * 将 timestamp 类型改为 datetime 类型，时间格式为 2026-02-05 12:22:22
 *
 * 运行: cd server && pnpm exec tsx src/scripts/fix-platform-accounts-timestamp.ts
 */
import { initDatabase, AppDataSource } from '../models/index.js';
import { logger } from '../utils/logger.js';

async function fixPlatformAccountsTimestamp() {
  try {
    await initDatabase();
    logger.info('数据库连接已初始化');

    const queryRunner = AppDataSource.createQueryRunner();
    await queryRunner.connect();

    try {
      logger.info('\n========================================');
      logger.info('修复 platform_accounts 时间字段格式...');
      logger.info('========================================\n');

      await queryRunner.query(`SET time_zone = '+08:00'`);

      logger.info('1. 修改 created_at 字段类型...');
      await queryRunner.query(`
        ALTER TABLE platform_accounts 
        MODIFY COLUMN created_at DATETIME NULL
      `);
      await queryRunner.query(`
        ALTER TABLE platform_accounts 
        MODIFY COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      `);
      logger.info('   ✓ created_at 修改完成');

      logger.info('2. 修改 updated_at 字段类型...');
      await queryRunner.query(`
        ALTER TABLE platform_accounts 
        MODIFY COLUMN updated_at DATETIME NULL
      `);
      await queryRunner.query(`
        ALTER TABLE platform_accounts 
        MODIFY COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      `);
      logger.info('   ✓ updated_at 修改完成');

      logger.info('\n3. 验证修复结果...');
      const rows = await queryRunner.query(`
        SELECT id, account_name, created_at, updated_at 
        FROM platform_accounts 
        ORDER BY id DESC 
        LIMIT 5
      `);
      rows.forEach((row: any) => {
        logger.info(`   ID ${row.id}: created_at=${row.created_at}, updated_at=${row.updated_at}`);
      });

      logger.info('\n========================================');
      logger.info('platform_accounts 时间字段修复完成！');
      logger.info('========================================\n');
    } catch (error: any) {
      logger.error('修复过程中出错:', error);
      throw error;
    } finally {
      await queryRunner.release();
    }
  } catch (error: any) {
    logger.error('修复失败:', error);
    process.exit(1);
  } finally {
    await AppDataSource.destroy();
    process.exit(0);
  }
}

fixPlatformAccountsTimestamp().catch(console.error);
