import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Per-truck EDR last-mile handovers. `truck_assignment_id` FKs
 * customer_truck_assignments (self-haul only), so EDR trucks need their own
 * link to the last-mile vehicle assignment that hauled the goods. Generated
 * when the EDR truck exits the warehouse (with its exit paper) and signed by
 * the customer in the portal — one per truck, or booking-level (both ids null)
 * when the truck cannot be resolved.
 */
export class AddHandoverEdrAssignment2440000000000 implements MigrationInterface {
  name = 'AddHandoverEdrAssignment2440000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.booking_handovers
        ADD COLUMN IF NOT EXISTS edr_assignment_id uuid
          REFERENCES freight.last_mile_vehicle_assignments(id) ON DELETE SET NULL;
    `);
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_booking_handovers_booking_edr_truck"
      ON freight.booking_handovers (booking_id, edr_assignment_id)
      WHERE deleted_at IS NULL AND edr_assignment_id IS NOT NULL;
    `);
  }

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