import { Booking } from './entities/booking.entity';

/**
 * Resolves which seeded clearance FileUploadSetting applies to a booking, from
 * its trade direction, freight type and whether its service includes customs.
 * Mirrors the codes seeded in file-upload-settings.seeder.ts.
 */

type Op = 'import' | 'export';
type Freight = 'container' | 'bulk';

/** Trade direction → clearance operation. DOMESTIC has no customs clearance. */
function operationFor(tradeDirection: string): Op | null {
  if (tradeDirection === 'IMPORT') return 'import';
  if (tradeDirection === 'EXPORT') return 'export';
  return null; // DOMESTIC / intercity — no clearance gate
}

function freightFor(freightType: string): Freight {
  return freightType === 'BULK' ? 'bulk' : 'container';
}

/** The customer-input clearance setting code, or null when no gate applies. */
export function clearanceSettingCode(
  tradeDirection: string,
  freightType: string,
  includesCustoms: boolean,
): string | null {
  const op = operationFor(tradeDirection);
  if (!op) return null;
  const freight = freightFor(freightType);
  const customs = includesCustoms ? 'with_customs' : 'without_customs';
  return `clearance_${op}_${freight}_${customs}`;
}

/** The GL-output (customs output) setting code; only container customs sets exist. */
export function clearanceOutputSettingCode(
  tradeDirection: string,
  freightType: string,
  includesCustoms: boolean,
): string | null {
  if (!includesCustoms) return null;
  const op = operationFor(tradeDirection);
  if (!op) return null;
  // Only container customs output sets are seeded for this phase.
  if (freightFor(freightType) !== 'container') return null;
  return `clearance_output_${op}_container`;
}

/** Convenience: resolve both codes for a loaded booking (with its serviceType). */
export function clearanceCodesForBooking(booking: Booking): {
  inputCode: string | null;
  outputCode: string | null;
  includesCustoms: boolean;
} {
  const includesCustoms = booking.serviceType?.includesCustoms ?? false;
  return {
    inputCode: clearanceSettingCode(
      booking.tradeDirection,
      booking.freightType,
      includesCustoms,
    ),
    outputCode: clearanceOutputSettingCode(
      booking.tradeDirection,
      booking.freightType,
      includesCustoms,
    ),
    includesCustoms,
  };
}
