import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index } from 'typeorm';

export const HANDOVER_MILE_TYPES = ['SELF_HAUL', 'EDR_LAST_MILE'] as const;
export type HandoverMileType = (typeof HANDOVER_MILE_TYPES)[number];

/**
 * One import handover. A booking has a single handover when one truck takes the
 * whole booking (`truckAssignmentId` null = per-booking), or one per truck when
 * multiple trucks are used. Self-haul handovers are generated on truck arrival
 * and signed before the truck leaves; EDR last-mile handovers are generated
 * when the EDR truck exits the warehouse (with its exit paper) and signed by
 * the customer in the portal on delivery — one signature per truck.
 */
@Entity({ schema: 'freight', name: 'booking_handovers' })
@Index(['bookingId'])
export class BookingHandover extends BaseEntity {
  @Column({ name: 'booking_id', type: 'uuid' })
  bookingId!: string;

  /** Customer self-haul truck this handover belongs to; null = per-booking. */
  @Column({ name: 'truck_assignment_id', type: 'uuid', nullable: true })
  truckAssignmentId?: string | null;

  /** EDR last-mile vehicle assignment this handover belongs to; null = per-booking. */
  @Column({ name: 'edr_assignment_id', type: 'uuid', nullable: true })
  edrAssignmentId?: string | null;

  /** Denormalised plate for display / EDR trucks (which aren't customer trucks). */
  @Column({ name: 'truck_plate', type: 'varchar', length: 32, nullable: true })
  truckPlate?: string | null;

  @Column({ name: 'mile_type', type: 'varchar', length: 20 })
  mileType!: HandoverMileType;

  @Column({ name: 'reference', type: 'varchar', length: 100 })
  reference!: string;

  @Column({ name: 'generated_at', type: 'timestamptz', default: () => 'now()' })
  generatedAt!: Date;

  @Column({ name: 'signed_at', type: 'timestamptz', nullable: true })
  signedAt?: Date | null;

  /** Full name of the person who signed off the handover (required at sign time). */
  @Column({ name: 'signer_name', type: 'varchar', length: 160, nullable: true })
  signerName?: string | null;

  @Column({ name: 'signed_by_user_id', type: 'uuid', nullable: true })
  signedByUserId?: string | null;

  /** EDR last-mile: when the goods were delivered to the customer. */
  @Column({ name: 'delivered_at', type: 'timestamptz', nullable: true })
  deliveredAt?: Date | null;

  /** URL to the signer's saved signature image, if available at sign time. */
  @Column({ name: 'signature_image_url', type: 'text', nullable: true })
  signatureImageUrl?: string | null;
}
