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

import { Yard } from '../../rule-engine/entities/yard.entity';
import { TrainSchedule } from '../../train-schedules/entities/train-schedule.entity';

/**
 * One staff-logged tracking checkpoint for a dispatched train as it passes a
 * station along its route (origin → milestones → destination).
 */
@Entity({ schema: 'freight', name: 'train_checkpoint_events' })
@Index(['trainScheduleId'])
@Index(['trainScheduleId', 'sequenceNo'])
export class TrainCheckpointEvent extends BaseEntity {
  @Column({ name: 'train_schedule_id', type: 'uuid' })
  trainScheduleId!: string;

  @ManyToOne(() => TrainSchedule, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'train_schedule_id' })
  trainSchedule?: TrainSchedule;

  @Column({ name: 'yard_id', type: 'uuid' })
  yardId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'yard_id' })
  yard?: Yard;

  /** Position along the corridor: 0 = origin, N+1 = destination. */
  @Column({ name: 'sequence_no', type: 'int' })
  sequenceNo!: number;

  @Column({ name: 'kind', type: 'varchar', length: 20 })
  kind!: TrainCheckpointKind;

  @Column({ name: 'occurred_at', type: 'timestamptz' })
  occurredAt!: Date;

  @Column({ name: 'note', type: 'text', nullable: true })
  note?: string | null;

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