import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Structured import handover records. Replaces the ad-hoc handover notes so a
 * booking can carry one handover (single truck) or several (one per truck when
 * multiple trucks are used). Timing differs by mile type:
 *  - SELF_HAUL: generated on first truck arrival, signed before the truck leaves.
 *  - EDR_LAST_MILE: generated at delivery (after exit); signed on delivery.
 */
export class AddBookingHandovers1980000000000 implements MigrationInterface {
  name = 'AddBookingHandovers1980000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.booking_handovers (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        booking_id uuid NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE,
        truck_assignment_id uuid REFERENCES freight.customer_truck_assignments(id) ON DELETE SET NULL,
        truck_plate varchar(32),
        mile_type varchar(20) NOT NULL,
        reference varchar(100) NOT NULL,
        generated_at timestamptz NOT NULL DEFAULT now(),
        signed_at timestamptz,
        signed_by_user_id uuid,
        delivered_at timestamptz,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz
      );
    `);
    await queryRunner.query(
      `CREATE INDEX IF NOT EXISTS "IDX_booking_handovers_booking" ON freight.booking_handovers (booking_id);`,
    );
    // At most one live handover per (booking, customer truck). EDR trucks (which
    // aren't customer_truck_assignments) and per-booking handovers are de-duped
    // in the service, since a NULL truck_assignment_id can't be uniquely indexed.
    await queryRunner.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS "UQ_booking_handovers_booking_truck"
      ON freight.booking_handovers (booking_id, truck_assignment_id)
      WHERE deleted_at IS NULL AND truck_assignment_id IS NOT NULL;
    `);
  }

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