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

import { Yard } from '../../rule-engine/entities/yard.entity';
import { Route } from '../../routes/entities/route.entity';
import { TrainSet } from '../../train-sets/entities/train-set.entity';
import { TrainScheduleBooking } from './train-schedule-booking.entity';

export const TRAIN_SCHEDULE_STATUSES = [
  'DRAFT',
  'SCHEDULED',
  'DISPATCHED',
  'ARRIVED',
  'CANCELLED',
] as const;

export type TrainScheduleStatus = (typeof TRAIN_SCHEDULE_STATUSES)[number];

@Entity({ schema: 'freight', name: 'train_schedules' })
@Index(['scheduledDepartureDate'])
@Index(['status'])
export class TrainSchedule extends BaseEntity {
  @Column({ name: 'train_set_id', type: 'uuid', unique: true })
  trainSetId!: string;

  @OneToOne(() => TrainSet, (trainSet) => trainSet.trainSchedule)
  @JoinColumn({ name: 'train_set_id' })
  trainSet?: TrainSet;

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

  @ManyToOne(() => Route)
  @JoinColumn({ name: 'route_id' })
  route?: Route | null;

  @Column({ name: 'origin_station_id', type: 'uuid' })
  originStationId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'origin_station_id' })
  originStation?: Yard;

  @Column({ name: 'destination_station_id', type: 'uuid' })
  destinationStationId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'destination_station_id' })
  destinationStation?: Yard;

  @Column({ name: 'scheduled_departure_date', type: 'timestamptz' })
  scheduledDepartureDate!: Date;

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

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

  @OneToMany(() => TrainScheduleBooking, (scheduleBooking) => scheduleBooking.trainSchedule)
  scheduleBookings?: TrainScheduleBooking[];
}
