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

import { Vehicle } from '../../vehicles/entities/vehicle.entity';
import { FirstMile } from './first-mile.entity';

/**
 * One row per vehicle assigned to a first-mile pickup. A pickup can be served
 * by several vehicles at once (multi-truck bookings); the legacy
 * `first_mile.vehicle_id` column keeps pointing at the first assignment for
 * backward compatibility.
 */
@Entity({ name: 'first_mile_vehicle_assignments', schema: 'freight' })
@Unique(['firstMileId', 'vehicleId'])
@Index(['vehicleId'])
export class FirstMileVehicleAssignment extends BaseEntity {
  @Column({ name: 'first_mile_id', type: 'uuid' })
  firstMileId!: string;

  @ManyToOne(() => FirstMile, (fm) => fm.vehicleAssignments, { nullable: false, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'first_mile_id' })
  firstMile?: FirstMile;

  @Column({ name: 'vehicle_id', type: 'uuid' })
  vehicleId!: string;

  @ManyToOne(() => Vehicle, { nullable: false, eager: false })
  @JoinColumn({ name: 'vehicle_id' })
  vehicle?: Vehicle;

  /** Container this truck carries — auto-filled from the booking's container
   *  number when known, else entered manually at assignment time. */
  @Column({ name: 'container_number', type: 'varchar', nullable: true })
  containerNumber?: string | null;

  /** Actual distance driven by this truck (km), entered per vehicle. */
  @Column({ name: 'distance_km', type: 'numeric', precision: 10, scale: 2, nullable: true })
  distanceKm?: number | null;

  /** Bulk: tonnage this truck hauls — assigned tonnage draws down the booking total. */
  @Column({ name: 'tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  tons?: number | null;

  /** Bulk: optional item/piece count on this truck. */
  @Column({ name: 'quantity', type: 'integer', nullable: true })
  quantity?: number | null;
}
