import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Per-container receive tracking. A booking's containers arrive individually
 * (on separate self-haul trucks), so each container unit tracks whether it has
 * been received into the port and, once staff confirm it, the GRN it belongs to.
 * A single GRN covers the containers received together — so if the whole booking
 * arrives at once, all its units share one GRN (per-booking GRN).
 */
export class AddContainerReceiptToBookingContainerUnits1960000000000
  implements MigrationInterface
{
  name = 'AddContainerReceiptToBookingContainerUnits1960000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.booking_container_units
        ADD COLUMN IF NOT EXISTS received_to_port boolean NOT NULL DEFAULT false,
        ADD COLUMN IF NOT EXISTS received_at timestamptz,
        ADD COLUMN IF NOT EXISTS grn_number varchar(100)
    `);
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "IDX_booking_container_units_grn" ON freight.booking_container_units (grn_number);`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP INDEX IF EXISTS freight."IDX_booking_container_units_grn";`);
    await queryRunner.query(`
      ALTER TABLE freight.booking_container_units
        DROP COLUMN IF EXISTS received_to_port,
        DROP COLUMN IF EXISTS received_at,
        DROP COLUMN IF EXISTS grn_number
    `);
  }
}
