import { AppDataSource } from '../data-source';
import { SeedEdRWagonFleet1750400000000 } from '../migrations/1750400000000-SeedEdRWagonFleet';

async function seedEdRWagons() {
  await AppDataSource.initialize();

  const queryRunner = AppDataSource.createQueryRunner();

  try {
    await queryRunner.connect();
    await queryRunner.startTransaction();

    await new SeedEdRWagonFleet1750400000000().up(queryRunner);

    const [summary] = await queryRunner.query(`
      SELECT
        COUNT(*)::int AS total,
        COUNT(*) FILTER (WHERE wt.code = 'PW2')::int AS pw2,
        COUNT(*) FILTER (WHERE wt.code = 'CW4')::int AS cw4,
        COUNT(*) FILTER (WHERE wt.code = 'CW3')::int AS cw3,
        COUNT(*) FILTER (WHERE wt.code = 'KW2')::int AS kw2,
        COUNT(*) FILTER (WHERE wt.code = 'KW3')::int AS kw3,
        COUNT(*) FILTER (WHERE wt.code = 'NW5')::int AS nw5,
        COUNT(*) FILTER (WHERE wt.supported_load_types @> ARRAY['CONTAINER'])::int AS container_ready,
        COUNT(*) FILTER (WHERE wt.supported_load_types @> ARRAY['BULK'])::int AS bulk_ready,
        COUNT(*) FILTER (WHERE w.status = 'IMPORT_READY')::int AS import_ready
      FROM freight.wagons w
      JOIN freight.wagon_types wt ON wt.id = w.wagon_type_id
      WHERE w.wagon_number BETWEEN 'ER0001' AND 'ER0940';
    `);

    await queryRunner.commitTransaction();

    console.log('Seeded EDR wagon fleet:', summary);
  } catch (error) {
    await queryRunner.rollbackTransaction();
    throw error;
  } finally {
    await queryRunner.release();
    await AppDataSource.destroy();
  }
}

seedEdRWagons().catch((error) => {
  console.error('Failed to seed EDR wagon fleet:', error);
  process.exit(1);
});
