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

@Entity({ name: 'containers', schema: 'freight' })
export class Container extends BaseEntity {
  @Column({ unique: true, name: 'container_number' })
  containerNumber!: string;

  @Column({ name: 'container_type_id', type: 'uuid' })
  containerTypeId!: string;

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

  @Column({ type: 'int', nullable: true })
  position!: number | null; // position on the wagon (1..N)

  @Column({ name: 'tare_weight', type: 'decimal', precision: 10, scale: 2 })
  tareWeight!: number;

  @Column({ name: 'max_gross_weight', type: 'decimal', precision: 10, scale: 2 })
  maxGrossWeight!: number;

  @Column({
  name: 'seal_number',
  type: 'varchar',
  nullable: true,
})
sealNumber!: string | null;

  @Column({ type: 'varchar', default: 'AVAILABLE' })
  status!: string; // AVAILABLE, LOADED, IN_TRANSIT, MAINTENANCE, DAMAGED

  @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: '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_container_id', type: 'uuid', nullable: true })
  bookingContainerId!: string | null;

  @ManyToOne(() => BookingContainer, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'booking_container_id' })
  bookingContainer?: BookingContainer | null;

  @ManyToOne(() => Wagon, (wagon) => wagon.containers, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'wagon_id' })
  wagon!: Wagon | null;

  // Relationship to Cargo
  @OneToMany(() => Cargo, (cargo) => cargo.container)
  cargoes!: Cargo[];
}