import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Adds customer_truck_containers.loaded_at so an assignment (customer planning
 * which containers ride which truck) is distinct from the container actually
 * being loaded. Stage LOADED now requires loaded_at; customer assignment alone
 * keeps the container at its prior stage (RECEIVED/GRN) with its planned truck
 * shown. Backfills containers on already-departed trucks (they left loaded).
 */
export class AddCustomerTruckContainerLoadedAt2050000000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.customer_truck_containers
        ADD COLUMN IF NOT EXISTS loaded_at TIMESTAMPTZ;
    `);

    await queryRunner.query(`
      UPDATE freight.customer_truck_containers ctc
      SET loaded_at = a.departed_at
      FROM freight.customer_truck_assignments a
      WHERE a.id = ctc.assignment_id
        AND a.departed_at IS NOT NULL
        AND ctc.deleted_at IS NULL
        AND ctc.loaded_at IS NULL;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.customer_truck_containers DROP COLUMN IF EXISTS loaded_at;
    `);
  }
}
