import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Tare weight becomes mandatory on a wagon type.
 *
 * The locomotive's pull limit is a GROSS limit — it drags the wagon as well as
 * the cargo — so capacity math cannot run without a tare. A NULL tare silently
 * read as zero and let trains overbook by the tare fraction (~27% on a PW2
 * consist), so the column is now NOT NULL.
 *
 * Any row still missing a tare predates 2060000000000-SeedRailWagonTypes (which
 * upserts the ten real EDR types). Backfill those by code first, and give any
 * remaining custom/demo type the NW5 flat-wagon tare rather than fail the
 * migration — a wrong-but-plausible tare is recoverable in the admin UI; a
 * blocked deploy is not.
 */
export class MakeWagonTypeTareWeightRequired2070000000000 implements MigrationInterface {
  private readonly tareByCode: Array<[string, number]> = [
    ['NW7', 37.1],
    ['NW5', 22.4],
    ['PW2', 25.2],
    ['GW2', 23],
    ['CW4', 24.8],
    ['CW3', 23.4],
    ['KW2', 25.2],
    ['KW3', 24],
    ['NW6', 25.3],
    ['BW1', 32.1],
  ];

  /** NW5 flat wagon — the commonest type in the fleet (550 of 1100). */
  private readonly fallbackTareTons = 22.4;

  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const [code, tareWeightTons] of this.tareByCode) {
      await queryRunner.query(
        `UPDATE freight.wagon_types
            SET tare_weight_tons = $2
          WHERE code = $1 AND tare_weight_tons IS NULL;`,
        [code, tareWeightTons],
      );
    }

    await queryRunner.query(
      `UPDATE freight.wagon_types
          SET tare_weight_tons = $1
        WHERE tare_weight_tons IS NULL;`,
      [this.fallbackTareTons],
    );

    await queryRunner.query(
      `ALTER TABLE freight.wagon_types
         ALTER COLUMN tare_weight_tons SET NOT NULL;`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.wagon_types
         ALTER COLUMN tare_weight_tons DROP NOT NULL;`,
    );
  }
}
