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

import { Yard } from '../../rule-engine/entities/yard.entity';
import { Wagon } from './wagon.entity';
import { WagonTransferRequest } from './wagon-transfer-request.entity';

/**
 * Ledger of every physical wagon relocation between yards — one row per move.
 * Written when a wagon carries a booking's leg (LOADED), rides a train empty to
 * reposition (EMPTY_REPOSITION), or staff manually correct its yard (MANUAL).
 * `wagons.current_yard_id` is the derived "where is it now"; this table is the
 * auditable history of how it got there and by whom.
 */
@Entity({ schema: 'freight', name: 'wagon_movements' })
@Index(['wagonId', 'occurredAt'])
export class WagonMovement extends BaseEntity {
  @Column({ name: 'wagon_id', type: 'uuid' })
  wagonId!: string;

  @ManyToOne(() => Wagon, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'wagon_id' })
  wagon?: Wagon;

  /** Null when the prior location is unknown (e.g. first manual registration). */
  @Column({ name: 'from_yard_id', type: 'uuid', nullable: true })
  fromYardId?: string | null;

  @ManyToOne(() => Yard, { nullable: true })
  @JoinColumn({ name: 'from_yard_id' })
  fromYard?: Yard | null;

  @Column({ name: 'to_yard_id', type: 'uuid' })
  toYardId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'to_yard_id' })
  toYard?: Yard | null;

  /** Set when the move happened by riding a scheduled train (LOADED / EMPTY_REPOSITION). */
  @Column({ name: 'train_schedule_id', type: 'uuid', nullable: true })
  trainScheduleId?: string | null;

  /** Set when the move carried a specific booking's cargo (kind LOADED). */
  @Column({ name: 'booking_id', type: 'uuid', nullable: true })
  bookingId?: string | null;

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

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

  /** The transfer request this move fulfilled, when it came from one. */
  @Column({ name: 'transfer_request_id', type: 'uuid', nullable: true })
  transferRequestId?: string | null;

  @ManyToOne(() => WagonTransferRequest, { nullable: true })
  @JoinColumn({ name: 'transfer_request_id' })
  transferRequest?: WagonTransferRequest | null;

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

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