import { DataSource } from 'typeorm';
import { InitialSchema1784520727860 } from './migrations/1784520727860-InitialSchema';
import { AddExamManagement1784600000000 } from './migrations/1784600000000-AddExamManagement';
import { AddRoomInspections1784680000000 } from './migrations/1784680000000-AddRoomInspections';
import { AddJinshujuMatchRules1784700000000 } from './migrations/1784700000000-AddJinshujuMatchRules';
import { AddAiChat1784780000000 } from './migrations/1784780000000-AddAiChat';
import { EnhanceAiChatForAntDesignX1784860000000 } from './migrations/1784860000000-EnhanceAiChatForAntDesignX';
import { AddA2UiForms1784870000000 } from './migrations/1784870000000-AddA2UiForms';
import { AddA2UiReviews1784880000000 } from './migrations/1784880000000-AddA2UiReviews';
import { EnlargeAiReviewSections1784900000000 } from './migrations/1784900000000-EnlargeAiReviewSections';
import { config } from 'dotenv';

config();

const isMySQL = (process.env.DB_TYPE || 'sqlite') === 'mysql';

export async function runMigrationsOnStartup(): Promise<void> {
  // 该迁移由 MySQL 生成；SQLite 开发环境由 AppModule 中的 TypeORM synchronize 建表。
  if (!isMySQL) return;

  const ds = new DataSource({
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT || 3306),
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_DATABASE || 'dorm_billing',
    charset: 'utf8mb4',
    migrations: [
      InitialSchema1784520727860,
      AddExamManagement1784600000000,
      AddRoomInspections1784680000000,
      AddJinshujuMatchRules1784700000000,
      AddAiChat1784780000000,
      EnhanceAiChatForAntDesignX1784860000000,
      AddA2UiForms1784870000000,
      AddA2UiReviews1784880000000,
      EnlargeAiReviewSections1784900000000,
    ],
  });

  await ds.initialize();
  await ds.runMigrations();
  await ds.destroy();
}
