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

import { Facility } from '../../facilities/entities/facility.entity';
import { WarehouseYard } from './warehouse-yard.entity';

export const WAREHOUSE_TYPES = ['OPEN_WAREHOUSE', 'CLOSED_WAREHOUSE'] as const;
export type WarehouseType = (typeof WAREHOUSE_TYPES)[number];

export const WAREHOUSE_STATUSES = ['ACTIVE', 'INACTIVE'] as const;
export type WarehouseStatus = (typeof WAREHOUSE_STATUSES)[number];

@Entity({ schema: 'freight', name: 'warehouses' })
@Index(['code'], { unique: true })
@Index(['type'])
@Index(['status'])
@Index(['stationId'])
export class Warehouse extends BaseEntity {
  @Column({ name: 'name', type: 'varchar', length: 160 })
  name!: string;

  @Column({ name: 'code', type: 'varchar', length: 40, unique: true })
  code!: string;

  @Column({ name: 'type', type: 'varchar', length: 32 })
  type!: WarehouseType;

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

  @Column({ name: 'location_name', type: 'varchar', length: 200, nullable: true })
  locationName?: string | null;

  @Column({ name: 'capacity_weight', type: 'numeric', precision: 14, scale: 3, nullable: true })
  capacityWeight?: number | null;

  @Column({ name: 'capacity_containers', type: 'int', nullable: true })
  capacityContainers?: number | null;

  @Column({ name: 'current_weight', type: 'numeric', precision: 14, scale: 3, default: 0 })
  currentWeight!: number;

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

  // Batch 2 capacity (weight + volume). maxWeight backfilled from capacityWeight.
  @Column({ name: 'max_weight', type: 'numeric', precision: 14, scale: 3, nullable: true })
  maxWeight?: number | null;

  @Column({ name: 'max_volume', type: 'numeric', precision: 14, scale: 3, nullable: true })
  maxVolume?: number | null;

  @Column({ name: 'current_volume', type: 'numeric', precision: 14, scale: 3, default: 0 })
  currentVolume!: number;

  @Column({ name: 'status', type: 'varchar', length: 16, default: 'ACTIVE' })
  status!: WarehouseStatus;

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

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

  @ManyToOne(() => Facility, (facility) => facility.warehouses, { nullable: true })
  @JoinColumn({ name: 'facility_id' })
  facility?: Facility | null;

  @OneToMany(() => WarehouseYard, (yard) => yard.warehouse)
  yards?: WarehouseYard[];
}
