import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Per-truck exit weights for customer self-haul, mirroring what
 * `last_mile_vehicle_assignments` already carries for EDR trucks.
 *
 * A bulk booking is hauled away truck by truck until no tonnage is left, and the
 * EDR side enforces that by summing `net_weight_tons` of departed trucks. The
 * customer side had no net and no tare — only `gross_weight_kg`, which nothing
 * in the live flow ever wrote (the release flow updated the EDR table only). So
 * a self-haul bulk booking could take unlimited trucks: hauled tonnage always
 * summed to zero.
 *
 * `gross_weight_kg` is left alone but note it holds TONNES despite its name —
 * the weighing UI is in tonnes throughout. The new columns are named for the
 * unit they actually hold.
 */
export class AddCustomerTruckExitWeights2400000000000 implements MigrationInterface {
  name = 'AddCustomerTruckExitWeights2400000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.customer_truck_assignments
        ADD COLUMN IF NOT EXISTS tare_weight_tons numeric(14,3) NULL,
        ADD COLUMN IF NOT EXISTS net_weight_tons  numeric(14,3) NULL
    `);

    // Departed trucks are what the drawdown sums, so it reads this index.
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_customer_truck_departed"
        ON freight.customer_truck_assignments (booking_id, departed_at)
        WHERE deleted_at IS NULL
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DROP INDEX IF EXISTS freight."IDX_customer_truck_departed"`,
    );
    await queryRunner.query(`
      ALTER TABLE freight.customer_truck_assignments
        DROP COLUMN IF EXISTS tare_weight_tons,
        DROP COLUMN IF EXISTS net_weight_tons
    `);
  }
}
