// apps/edr-freight-api/src/modules/cargoes/entities/cargo.entity.ts
import { Entity, Column, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '@edr/api-common';
import { Booking } from '../../bookings/entities/booking.entity';
import { Container } from '../../container-management/entities/container.entity';
import { WagonBookingAllocation } from '../../train-schedules/entities/wagon-booking-allocation.entity';

@Entity({ name: 'cargoes', schema: 'freight' })
export class Cargo extends BaseEntity {
  @Column({ unique: true, name: 'cargo_reference' })
  cargoReference!: string;

  @Column({ name: 'shipment_id', type: 'uuid' })
  shipmentId!: string;

  @Column({ name: 'container_id', type: 'uuid', nullable: true })
  containerId!: string | null;

  @Column({ name: 'cargo_type_id', type: 'uuid', nullable: true })
  cargoTypeId!: string | null; // optional link to cargo_types table

  @Column({ type: 'text', nullable: true })
  description!: string | null;

  @Column({ type: 'decimal', precision: 12, scale: 3 })
  quantity!: number;

  @Column({ type: 'decimal', precision: 10, scale: 2 })
  weight!: number; // kg

  @Column({ type: 'decimal', precision: 10, scale: 2, nullable: true })
  volume!: number | null; // m³

  @Column({ type: 'varchar', default: 'PENDING' })
  status!: string; // PENDING, LOADED, IN_TRANSIT, DELIVERED, UNLOADED

  @Column({ name: 'loaded_at', type: 'timestamp', nullable: true })
  loadedAt!: Date | null;

  @Column({ name: 'unloaded_at', type: 'timestamp', nullable: true })
  unloadedAt!: Date | null;

  // Proof of Delivery (customer pickup) capture.
  @Column({ name: 'receiver_name', type: 'varchar', nullable: true })
  receiverName!: string | null;

  @Column({ name: 'delivered_at', type: 'timestamp', nullable: true })
  deliveredAt!: Date | null;

  @Column({ name: 'delivery_remarks', type: 'text', nullable: true })
  deliveryRemarks!: string | null;

  @Column({ name: 'wagon_booking_allocation_id', type: 'uuid', nullable: true })
  wagonBookingAllocationId!: string | null;

  @ManyToOne(() => WagonBookingAllocation, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'wagon_booking_allocation_id' })
  wagonBookingAllocation?: WagonBookingAllocation | null;

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

  @ManyToOne(() => Booking, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'booking_id' })
  booking?: Booking | null;

  @Column({ name: 'load_type', type: 'varchar', length: 20, nullable: true })
  loadType!: string | null;

  // Relationship to Container
  @ManyToOne(() => Container, (container) => container.cargoes, { onDelete: 'RESTRICT', nullable: true })
  @JoinColumn({ name: 'container_id' })
  container!: Container | null;
}