import { DataSource } from 'typeorm';
import { InitialSchema1784520727860 } from './migrations/1784520727860-InitialSchema';
import { config } from 'dotenv';

config();

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

export async function runMigrationsOnStartup(): Promise<void> {
  const ds = new DataSource({
    type: isMySQL ? 'mysql' : 'better-sqlite3',
    host: isMySQL ? (process.env.DB_HOST || 'localhost') : undefined,
    port: isMySQL ? Number(process.env.DB_PORT || 3306) : undefined,
    username: isMySQL ? (process.env.DB_USERNAME || 'root') : undefined,
    password: isMySQL ? (process.env.DB_PASSWORD || '') : undefined,
    database: process.env.DB_DATABASE || (isMySQL ? 'dorm_billing' : 'dorm_billing.db'),
    charset: isMySQL ? 'utf8mb4' : undefined,
    migrations: [InitialSchema1784520727860],
  });

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