import { WagonType } from '../wagon-types/entities/wagon-type.entity';

const CARGO_CODE_TO_WAGON_TYPE: Record<string, string> = {
  COFFEE: 'KW2',
  GRAIN: 'KW2',
  WHEAT: 'KW2',
  SORGHUM: 'KW2',
  CORN: 'KW2',
  FERTILIZER: 'PW2',
  SUGAR: 'PW2',
  COAL: 'KW3',
  STEEL: 'CW3',
  ORE: 'CW3',
};

const DEFAULT_BULK_WAGON_TYPE = 'CW3';
const DEFAULT_CONTAINER_WAGON_TYPE = 'NW5';

/**
 * Resolve wagon type code from cargo type code for bulk freight.
 */
export function resolveBulkWagonTypeCode(cargoTypeCode?: string | null): string {
  if (!cargoTypeCode) return DEFAULT_BULK_WAGON_TYPE;
  const normalized = cargoTypeCode.trim().toUpperCase();
  return CARGO_CODE_TO_WAGON_TYPE[normalized] ?? DEFAULT_BULK_WAGON_TYPE;
}

/**
 * Pick the best matching wagon type entity for bulk cargo.
 */
export function pickBulkWagonType(
  wagonTypes: WagonType[],
  cargoTypeCode?: string | null,
): WagonType | undefined {
  const preferredCode = resolveBulkWagonTypeCode(cargoTypeCode);
  const direct = wagonTypes.find((wt) => wt.code === preferredCode && wt.isActive);
  if (direct) return direct;

  return wagonTypes.find(
    (wt) =>
      wt.isActive &&
      !wt.supportsContainer &&
      wt.code !== DEFAULT_CONTAINER_WAGON_TYPE,
  );
}

export function getDefaultContainerWagonTypeCode(): string {
  return DEFAULT_CONTAINER_WAGON_TYPE;
}
