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

import { CustomerTruckAssignment } from './customer-truck-assignment.entity';

/**
 * A container number loaded onto a customer truck. A container may be loaded
 * onto exactly one truck per booking (enforced by a partial unique index on
 * booking_id + container_number).
 */
@Entity({ schema: 'freight', name: 'customer_truck_containers' })
@Index(['assignmentId'])
export class CustomerTruckContainer extends BaseEntity {
  @Column({ name: 'assignment_id', type: 'uuid' })
  assignmentId!: string;

  @ManyToOne(() => CustomerTruckAssignment, (a) => a.containers, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'assignment_id' })
  assignment?: CustomerTruckAssignment;

  @Column({ name: 'booking_id', type: 'uuid' })
  bookingId!: string;

  @Column({ name: 'container_number', type: 'varchar', length: 64 })
  containerNumber!: string;

  /**
   * When the container was actually loaded onto the truck by the operator.
   * Null = customer-assigned (planned) but not yet loaded. Stage LOADED requires
   * this to be set, so customer assignment alone does not mark a container loaded.
   */
  @Column({ name: 'loaded_at', type: 'timestamptz', nullable: true })
  loadedAt?: Date | null;
}
