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

import { Booking } from './booking.entity';
import { CustomerTruckContainer } from './customer-truck-container.entity';

/**
 * One external (self-haul) truck a customer assigns to a booking that has no
 * EDR first/last-mile leg. Each truck carries 1–2 containers and tracks its own
 * arrival at the terminal/warehouse.
 */
@Entity({ schema: 'freight', name: 'customer_truck_assignments' })
@Index(['bookingId'])
export class CustomerTruckAssignment extends BaseEntity {
  @Column({ name: 'booking_id', type: 'uuid' })
  bookingId!: string;

  @ManyToOne(() => Booking, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'booking_id' })
  booking?: Booking;

  @Column({ name: 'plate_number', type: 'varchar', length: 32 })
  plateNumber!: string;

  @Column({ name: 'driver_name', type: 'varchar', length: 120 })
  driverName!: string;

  @Column({ name: 'truck_type', type: 'varchar', length: 60 })
  truckType!: string;

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

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

  /** Weighed gross of what the truck actually loaded (import), captured on
   *  leaving. Null until the truck departs. */
  @Column({ name: 'gross_weight_kg', type: 'numeric', precision: 14, scale: 2, nullable: true })
  grossWeightKg?: number | null;

  /** Empty truck weight at the gate, in tonnes. Null until the truck departs. */
  @Column({ name: 'tare_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  tareWeightTons?: number | null;

  /**
   * Cargo actually taken (gross − tare), in tonnes. Drives the bulk drawdown:
   * a bulk booking is hauled until the sum of this across departed trucks
   * reaches its declared VGM. Mirrors last_mile_vehicle_assignments.
   */
  @Column({ name: 'net_weight_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  netWeightTons?: number | null;

  /** Bulk: planned tonnage at assignment — draws down the booking before weigh-out. */
  @Column({ name: 'planned_tons', type: 'numeric', precision: 14, scale: 3, nullable: true })
  plannedTons?: number | null;

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

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

  @OneToMany(() => CustomerTruckContainer, (c) => c.assignment, { cascade: true })
  containers?: CustomerTruckContainer[];
}
