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 { 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,
    ],
  });

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