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

import { Yard } from './yard.entity';

/**
 * Configured rail distance between two yards. Route creation reads segment
 * kilometres from here (symmetric: A→B serves B→A too) instead of taking
 * them as free-text input — see RoutesService.validateMilestones.
 *
 * Uniqueness on (from_yard_id, to_yard_id) is a partial index in the DB
 * (WHERE deleted_at IS NULL) rather than a @Unique decorator, so a
 * soft-deleted pair can be re-created.
 */
@Entity({ schema: 'freight', name: 'yard_distances' })
@Index(['fromYardId'])
@Index(['toYardId'])
export class YardDistance extends BaseEntity {
  @Column({ name: 'from_yard_id', type: 'uuid' })
  fromYardId!: string;

  @ManyToOne(() => Yard)
  @JoinColumn({ name: 'from_yard_id' })
  fromYard?: Yard;

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

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

  @Column({ name: 'distance_km', type: 'decimal', precision: 10, scale: 2 })
  distanceKm!: string; // decimal columns come back as string in typeorm/pg — keep consistent with RouteMilestone.distanceKm
}
