const { DataSource } = require('typeorm');
const path = require('path');

const AppDataSource = new DataSource({
  type: 'postgres',
  host: process.env.DATABASE_HOST,
  port: parseInt(process.env.DATABASE_PORT, 10),
  username: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME,
  entities: [path.join(__dirname, 'dist/**/*.orm-entity.js')],
  migrations: [path.join(__dirname, 'dist/infrastructure/persistence/typeorm/migrations/*.js')],
  synchronize: false,
  logging: true,
});

console.log('🚀 Starting Xpeditis Backend Migration Script...');
console.log('📦 Initializing DataSource...');

AppDataSource.initialize()
  .then(async () => {
    console.log('✅ DataSource initialized successfully');
    console.log('🔄 Running pending migrations...');

    const migrations = await AppDataSource.runMigrations();

    if (migrations.length === 0) {
      console.log('✅ No pending migrations');
    } else {
      console.log(`✅ Successfully ran ${migrations.length} migration(s):`);
      migrations.forEach(migration => {
        console.log(`   - ${migration.name}`);
      });
    }

    await AppDataSource.destroy();
    console.log('✅ Database migrations completed successfully');
    process.exit(0);
  })
  .catch(error => {
    console.error('❌ Error during migration:');
    console.error(error);
    process.exit(1);
  });
