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

import { Booking } from '../../bookings/entities/booking.entity';
import { TrainSetWagon } from '../../train-sets/entities/train-set-wagon.entity';
import { WagonAllocationContainerItem } from './wagon-allocation-container-item.entity';

export const ALLOCATION_LOAD_TYPES = [
  AllocationLoadType.Container,
  AllocationLoadType.Bulk,
] as const;

export const ALLOCATION_STATUSES = [
  AllocationStatus.Planned,
  AllocationStatus.Reserved,
  AllocationStatus.Loaded,
  AllocationStatus.Departed,
] as const;

@Entity({ schema: 'freight', name: 'wagon_booking_allocations' })
@Index(['trainSetWagonId', 'bookingId'])
export class WagonBookingAllocation extends BaseEntity {
  @Column({ name: 'train_set_wagon_id', type: 'uuid' })
  trainSetWagonId!: string;

  @ManyToOne(() => TrainSetWagon, (wagon) => wagon.allocations, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'train_set_wagon_id' })
  trainSetWagon?: TrainSetWagon;

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

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

  @Column({ name: 'allocated_weight_tons', type: 'numeric', precision: 10, scale: 3 })
  allocatedWeightTons!: number;

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

  @Column({ name: 'status', type: 'varchar', length: 20, default: 'PLANNED' })
  status!: string;

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

  @Column({ name: 'confirmed_by_user_id', type: 'uuid', nullable: true })
  confirmedByUserId?: string | null;

  @OneToMany(() => WagonAllocationContainerItem, (item) => item.allocation)
  containerItems?: WagonAllocationContainerItem[];
}
