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

import { Vehicle } from '../../vehicles/entities/vehicle.entity';
import { LastMile } from './last-mile.entity';
import { LastMileVehicleContainer } from './last-mile-vehicle-container.entity';

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

  @ManyToOne(() => LastMile, (lm) => lm.vehicleAssignments, { nullable: false, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'last_mile_id' })
  lastMile?: LastMile;

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

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

  /** Legacy single container this truck carries. Kept in sync with the FIRST
   *  entry of `containers` for backward compatibility — a truck can hold 1x40ft
   *  or 2x20ft, so `containers` is the authoritative list. */
  @Column({ name: 'container_number', type: 'varchar', nullable: true })
  containerNumber?: string | null;

  /** Containers riding this truck (1x40ft, or up to 2x20ft). */
  @OneToMany(() => LastMileVehicleContainer, (c) => c.assignment, { cascade: true })
  containers?: LastMileVehicleContainer[];

  /** 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;

  /** This truck reached the warehouse (stamped by the arrival weighing step). */
  @Column({ name: 'arrived_at', type: 'timestamptz', nullable: true })
  arrivedAt?: Date | null;

  /** This truck left the warehouse (stamped by the exit weighing step). */
  @Column({ name: 'departed_at', type: 'timestamptz', nullable: true })
  departedAt?: Date | null;

  /** Weighed gross on exit, in TONNES (not kg — see the migration note). */
  @Column({ name: 'gross_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  grossWeightTons?: number | null;

  /** Cargo actually taken by this truck (gross − tare), in TONNES. Drives the
   *  bulk drawdown: remaining = booking VGM − SUM(net) over departed trucks. */
  @Column({ name: 'net_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  netWeightTons?: number | null;
}
