import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Upserts the 10 real EDR wagon types (code, name, capacity, length, tare
 * weight) by code. Overwrites any existing row with the same code so
 * previously-seeded demo values (e.g. NW5/PW2/CW3 from demo-bookings.seeder)
 * are replaced with the real spec.
 */
export class SeedRailWagonTypes2060000000000 implements MigrationInterface {
  private readonly wagonTypes = [
    { code: 'NW7', name: 'Double deck sedan wagon', capacityTons: 22, lengthMeters: 26.066, tareWeightTons: 37.1 },
    { code: 'NW5', name: 'Flat wagon', capacityTons: 70, lengthMeters: 13.966, tareWeightTons: 22.4 },
    { code: 'PW2', name: 'Box wagon', capacityTons: 70, lengthMeters: 17.066, tareWeightTons: 25.2 },
    { code: 'GW2', name: 'Tank wagon', capacityTons: 70, lengthMeters: 12.228, tareWeightTons: 23 },
    { code: 'CW4', name: 'Gondola covered wagon', capacityTons: 70, lengthMeters: 13.976, tareWeightTons: 24.8 },
    { code: 'CW3', name: 'Gondola open wagon', capacityTons: 70, lengthMeters: 13.976, tareWeightTons: 23.4 },
    { code: 'KW2', name: 'Hopper covered wagon', capacityTons: 69, lengthMeters: 16.466, tareWeightTons: 25.2 },
    { code: 'KW3', name: 'Hopper wagon open', capacityTons: 70, lengthMeters: 14.4, tareWeightTons: 24 },
    { code: 'NW6', name: 'Flat wagon (long)', capacityTons: 70, lengthMeters: 18.56, tareWeightTons: 25.3 },
    { code: 'BW1', name: 'Refrigerated wagon', capacityTons: 38, lengthMeters: 21.996, tareWeightTons: 32.1 },
  ];

  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const wt of this.wagonTypes) {
      await queryRunner.query(
        `
        INSERT INTO freight.wagon_types (code, name, capacity_tons, length_meters, tare_weight_tons, is_active)
        VALUES ($1, $2, $3, $4, $5, true)
        ON CONFLICT (code) DO UPDATE SET
          name = EXCLUDED.name,
          capacity_tons = EXCLUDED.capacity_tons,
          length_meters = EXCLUDED.length_meters,
          tare_weight_tons = EXCLUDED.tare_weight_tons;
        `,
        [wt.code, wt.name, wt.capacityTons, wt.lengthMeters, wt.tareWeightTons],
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DELETE FROM freight.wagon_types WHERE code = ANY($1);`,
      [this.wagonTypes.map((wt) => wt.code)],
    );
  }
}
