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

@Entity({ schema: 'freight', name: 'cargo_types' })
@Index(['isActive'])
@Index(['displayOrder'])
@Index(['parentGroupId'])
@Index(['code'])
export class CargoType extends BaseEntity {
  @Column({ name: 'code', type: 'varchar', length: 50, unique: true, default: '' })
  code!: string;

  @Column({ name: 'cargo_type_name', type: 'varchar', length: 255 })
  cargoTypeName!: string;

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

  @Column({ name: 'show_free_text_box', type: 'boolean', default: false })
  showFreeTextBox!: boolean;

  /**
   * How this cargo's quantity is measured: PER_TON (bulk) or PER_ITEM
   * (break-bulk). Nullable for container/legacy cargo, which is counted by
   * container. Drives the unit shown when ordering against a general contract.
   */
  @Column({ name: 'unit_of_measure', type: 'varchar', length: 16, nullable: true })
  unitOfMeasure?: CargoUnitOfMeasure | null;

  @Column({ name: 'requires_director_approval', type: 'boolean', default: false })
  requiresDirectorApproval!: boolean;

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

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

  @ManyToOne(() => CargoType, (ct) => ct.children, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'parent_group_id' })
  parent?: CargoType | null;

  @OneToMany(() => CargoType, (ct) => ct.parent)
  children?: CargoType[];
}
