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

import { Locomotive } from '../../locomotives/entities/locomotive.entity';
import { Train } from './train.entity';

/**
 * Link row joining a built train to one of its locomotives. A train must be
 * pulled by at least two locomotives (front + back); `sequenceNo` is the order
 * in the consist — 0 is the lead locomotive.
 *
 * Mirrors `train_set_locomotives`, but for the persistent fleet `Train` built
 * in the Train Builder rather than the per-departure operational train set.
 */
@Entity({ schema: 'freight', name: 'train_locomotives' })
@Index(['trainId', 'locomotiveId'], { unique: true })
export class TrainLocomotive extends BaseEntity {
  @Column({ name: 'train_id', type: 'uuid' })
  trainId!: string;

  @ManyToOne(() => Train, (train) => train.locomotives, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'train_id' })
  train?: Train;

  @Column({ name: 'locomotive_id', type: 'uuid' })
  locomotiveId!: string;

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

  @Column({ name: 'sequence_no', type: 'int', default: 0 })
  sequenceNo!: number;
}
