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

import { Locomotive } from '../../locomotives/entities/locomotive.entity';
import { TrainSchedule } from '../../train-schedules/entities/train-schedule.entity';
import { TrainSetWagon } from './train-set-wagon.entity';

export const TRAIN_SET_STATUSES = [
  'DRAFT',
  'ASSIGNED',
  'DISPATCHED',
  'COMPLETED',
  'CANCELLED',
] as const;

export type TrainSetStatus = (typeof TRAIN_SET_STATUSES)[number];

@Entity({ schema: 'freight', name: 'train_sets' })
@Index(['locomotiveId'])
@Index(['status'])
export class TrainSet extends BaseEntity {
  @Column({ name: 'locomotive_id', type: 'uuid' })
  locomotiveId!: string;

  @ManyToOne(() => Locomotive, (locomotive) => locomotive.trainSets)
  @JoinColumn({ name: 'locomotive_id' })
  locomotive?: Locomotive;

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

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

  @Column({ name: 'wagon_count', type: 'int' })
  wagonCount!: number;

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

  @OneToMany(() => TrainSetWagon, (wagon) => wagon.trainSet)
  wagons?: TrainSetWagon[];

  @OneToOne(() => TrainSchedule, (schedule) => schedule.trainSet)
  trainSchedule?: TrainSchedule;
}
