import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinColumn, ManyToOne } from 'typeorm';
import { Booking } from '../../bookings/entities/booking.entity';
import { ContainerType } from '../../rule-engine/entities/container-type.entity';
import { Yard } from '../../rule-engine/entities/yard.entity';

/**
 * One contracted route+quantity line of a GENERAL contract. A general contract
 * may span several routes (e.g. Addis→Dire Dawa: 10, Modjo→Djibouti: 5); each
 * route reserves its own quantity pool. Drawdown orders pick one of these routes
 * and decrement that route's pool. One-time bookings do not use this — they keep
 * the single origin/destination on the booking itself.
 */
@Entity({ schema: 'freight', name: 'contract_route_lines' })
@Index(['contractBookingId'])
export class ContractRouteLine extends BaseEntity {
  /** The general contract (a Booking with bookingType = GENERAL_CONTRACT). */
  @Column({ name: 'contract_booking_id', type: 'uuid' })
  contractBookingId!: string;

  @ManyToOne(() => Booking)
  @JoinColumn({ name: 'contract_booking_id' })
  contractBooking?: Booking;

  @Column({ name: 'origin_yard_id', type: 'uuid' })
  originYardId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'origin_yard_id' })
  originYard?: Yard;

  @Column({ name: 'destination_yard_id', type: 'uuid' })
  destinationYardId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'destination_yard_id' })
  destinationYard?: Yard;

  /**
   * Container type this route line reserves (CONTAINER contracts); null for
   * BULK/BREAK_BULK, where the quantity is tons/items.
   */
  @Column({ name: 'container_type_id', type: 'uuid', nullable: true })
  containerTypeId?: string | null;

  @ManyToOne(() => ContainerType, { nullable: true })
  @JoinColumn({ name: 'container_type_id' })
  containerType?: ContainerType | null;

  /** Contracted quantity for this (route, container type): containers, tons, or items. */
  @Column({ name: 'quantity', type: 'numeric', precision: 12, scale: 3 })
  quantity!: number;

  /**
   * Road distance for this route, configured with the route. Road (truck)
   * drawdown orders bill KM × the PER_KM rate from this value. Null for
   * rail-only routes where KM is not billed.
   */
  @Column({ name: 'km', type: 'numeric', precision: 10, scale: 2, nullable: true })
  km?: number | null;
}
