import type { TFunction } from "i18next";

type SubstitutionResultLike = {
  code?: string | null;
  message?: string | null;
} | null | undefined;

/**
 * Maps pickOrder lot-substitution API (MessageResponse) to zh-TW via pickOrder namespace.
 * Handles dynamic English messages from PickOrderService.confirmLotSubstitution.
 */
export function translateLotSubstitutionFailure(
  t: TFunction<"pickOrder">,
  substitutionResult: SubstitutionResultLike
): string {
  if (!substitutionResult) {
    return String(t("Lot switch failed; pick line was not marked as checked."));
  }

  const code = substitutionResult.code ?? "";
  const message = (substitutionResult.message ?? "").trim();

  if (code === "LOT_UNAVAILABLE") {
    return String(
      t(
        "The scanned lot inventory line is unavailable. Cannot switch or bind; pick line was not updated."
      )
    );
  }

  if (!message) {
    return String(t("Lot switch failed; pick line was not marked as checked."));
  }

  let m = message.match(/^Pick order line (\d+) not found$/);
  if (m) {
    return String(t("Pick order line {{id}} not found", { id: m[1] }));
  }

  m = message.match(/^SuggestedPickLot not found for pickOrderLineId=(\d+)$/);
  if (m) {
    return String(
      t("SuggestedPickLot not found for pickOrderLineId {{polId}}", { polId: m[1] })
    );
  }

  m = message.match(/^SuggestedPickLot qty is invalid: (.+)$/);
  if (m) {
    return String(t("SuggestedPickLot qty is invalid: {{qty}}", { qty: m[1].trim() }));
  }

  m = message.match(/^Reject switch lot: available=(.+) < required=(.+)$/);
  if (m) {
    return String(
      t("Reject switch lot: available {{available}} less than required {{required}}", {
        available: m[1].trim(),
        required: m[2].trim(),
      })
    );
  }

  m = message.match(/^Reject switch lot: picked=(.+) already >= required=(.+)$/);
  if (m) {
    return String(
      t(
        "Reject switch lot: picked {{picked}} already greater or equal required {{required}}",
        {
          picked: m[1].trim(),
          required: m[2].trim(),
        }
      )
    );
  }

  const viaKey = t(message, { defaultValue: message });
  if (viaKey !== message) {
    return String(viaKey);
  }

  return message;
}
