import { MigrationInterface, QueryRunner } from 'typeorm';

/** 20ft = 0.5 wagon slots (2 per wagon); 40ft = 1.0 wagon slot (1 per wagon). */
export class FixContainerWagonsPerUnit1750800000000 implements MigrationInterface {
  name = 'FixContainerWagonsPerUnit1750800000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    const hasContainerTypes = await queryRunner.hasTable('freight.container_types');
    if (!hasContainerTypes) {
      return;
    }

    await queryRunner.query(`
      UPDATE freight.container_types
      SET wagons_per_unit = 0.50
      WHERE size_ft = 20 OR code LIKE '20%';
    `);
    await queryRunner.query(`
      UPDATE freight.container_types
      SET wagons_per_unit = 1.00
      WHERE size_ft = 40 OR code LIKE '40%';
    `);

    const hasBookingContainer = await queryRunner.hasTable('freight.booking_container');
    if (!hasBookingContainer) {
      return;
    }

    await queryRunner.query(`
      UPDATE freight.booking_container bc
      SET wagons_required = CEILING(bc.quantity * ct.wagons_per_unit)
      FROM freight.container_types ct
      WHERE ct.id = bc.container_type_id;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const hasContainerTypes = await queryRunner.hasTable('freight.container_types');
    if (!hasContainerTypes) {
      return;
    }

    await queryRunner.query(`
      UPDATE freight.container_types SET wagons_per_unit = 1.00;
    `);
  }
}
