import { BaseEntity } from '@edr/api-common';
import { Column, Entity, Index, JoinTable, ManyToMany, OneToMany } from 'typeorm';
import { WeightLimitRule } from './weight-limit-rule.entity';
import { WagonType } from '../../wagon-types/entities/wagon-type.entity';

@Entity({ schema: 'freight', name: 'container_types' })
@Index(['code'])
@Index(['isActive'])
export class ContainerType extends BaseEntity {
  @Column({ name: 'code', type: 'varchar', length: 20, unique: true })
  code!: string;

  @Column({ name: 'label', type: 'varchar', length: 100, nullable: true })
  label!: string;

  @Column({ name: 'size_ft', type: 'smallint', nullable: true })
  sizeFt!: number;

  @Column({ name: 'is_reefer', type: 'boolean', default: false, nullable: true })
  isReefer!: boolean;

  @Column({ name: 'is_open_top', type: 'boolean', default: false, nullable: true })
  isOpenTop!: boolean;

  /**
   * Wagon types that can carry this container (e.g. a 20ft rides NX70 or NW5).
   * Train scheduling resolves the container wagon type through this list,
   * picking whichever type the schedule's train (or yard) actually has.
   * Scheduling throws if a scheduled container type has none configured.
   */
  @ManyToMany(() => WagonType)
  @JoinTable({
    name: 'container_type_wagon_types',
    schema: 'freight',
    joinColumn: { name: 'container_type_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'wagon_type_id', referencedColumnName: 'id' },
  })
  wagonTypes?: WagonType[];

  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive!: boolean;

  @Column({ name: 'display_order', type: 'int', default: 1, nullable: true })
  displayOrder!: number;

  @OneToMany(() => WeightLimitRule, (rule) => rule.containerType)
  weightLimitRules?: WeightLimitRule[];
}
