import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * General-contract drawdown order fields:
 *  - booking_order_lines.hazardous_quantity / reefer_quantity — per-order counts
 *    the customer enters when toggling hazardous/reefer; drive the surcharge
 *    rates on the spawned child booking.
 *  - bookings.is_reefer — booking-level refrigerated flag so REEFER_SURCHARGE
 *    applies to a contract order even when the container type is not a reefer.
 *  - contract_route_lines.km — road distance configured with the route; road
 *    orders bill KM × the PER_KM rate.
 *
 * NOTE: the shared dev DB has no applied migration history, so these columns
 * are also hand-applied there. ADD COLUMN IF NOT EXISTS keeps that idempotent.
 */
export class AddGeneralContractOrderFields1820000000010
  implements MigrationInterface
{
  name = 'AddGeneralContractOrderFields1820000000010';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.booking_order_lines ADD COLUMN IF NOT EXISTS hazardous_quantity numeric(12,3) NOT NULL DEFAULT 0;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.booking_order_lines ADD COLUMN IF NOT EXISTS reefer_quantity numeric(12,3) NOT NULL DEFAULT 0;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings ADD COLUMN IF NOT EXISTS is_reefer boolean NOT NULL DEFAULT false;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.contract_route_lines ADD COLUMN IF NOT EXISTS km numeric(10,2);`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.contract_route_lines DROP COLUMN IF EXISTS km;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.bookings DROP COLUMN IF EXISTS is_reefer;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.booking_order_lines DROP COLUMN IF EXISTS reefer_quantity;`,
    );
    await queryRunner.query(
      `ALTER TABLE freight.booking_order_lines DROP COLUMN IF EXISTS hazardous_quantity;`,
    );
  }
}
