import type { RateAppliesTo, RateTrigger, RateType } from './rate.entity';

/**
 * Derive the legacy `rateType` string from the friendly form fields.
 *
 * `rateType` is still the key the pricing engine uses to look up base rail
 * freight (CONTAINER_IMPORT, BULK_EXPORT, …) and what gets snapshotted on a
 * booking. The configuration UI no longer asks for it directly — the admin
 * picks `appliesTo` + `tradeDirection` (+ `trigger` for surcharges) and we map
 * that to the canonical rateType here so both layers stay in agreement.
 */
export function deriveRateType(input: {
  appliesTo: RateAppliesTo;
  trigger: RateTrigger;
  tradeDirection?: string | null;
  /** Whether a bulk cargo (vs a container) was selected — disambiguates intercity. */
  isBulk?: boolean;
}): RateType {
  const { appliesTo, trigger, tradeDirection, isBulk } = input;

  // Surcharges (trigger ≠ ALWAYS) map to their dedicated rateType.
  if (trigger !== 'ALWAYS') {
    switch (trigger) {
      case 'HAZARDOUS':
        return 'HAZARD_SURCHARGE';
      case 'REEFER':
        return 'REEFER_SURCHARGE';
      case 'OVERWEIGHT':
        return 'OVERWEIGHT_PER_TON';
      case 'SHIPPING_LINE':
        return 'DOUBLE_HANDLING';
      case 'CONSOLIDATION':
        return 'LASHING';
      case 'CANCELLATION':
        return 'CANCELLATION_FEE';
      case 'DEMURRAGE':
        return 'DEMURRAGE';
      case 'PIL_EXTRA_FEE':
        return 'PIL_EXTRA_FEE';
    }
  }

  // Base freight (trigger = ALWAYS) maps by category + direction.
  const isExport = tradeDirection === 'EXPORT';
  switch (appliesTo) {
    case 'CONTAINER':
      return isExport ? 'CONTAINER_EXPORT' : 'CONTAINER_IMPORT';
    case 'BULK':
      return isExport ? 'BULK_EXPORT' : 'BULK_IMPORT';
    case 'INTERCITY':
      // Intercity has no trade direction; container vs bulk decided by which
      // scope field was filled (cargoTypeId → bulk, containerTypeId → container).
      return isBulk ? 'INTERCITY_BULK' : 'INTERCITY_CONTAINER';
    case 'FIRST_MILE':
      return 'FIRST_MILE';
    case 'LAST_MILE':
      return 'LAST_MILE';
    default:
      return 'CANCELLATION_FEE';
  }
}
