import { formatQty, formatWeight } from "./formatters.js";

function compactText(value, fallback = "-") {
  const text = String(value || "").trim();
  return text || fallback;
}

function sourceMaterialTrace(line) {
  const code = compactText(line?.source_material_code, "");
  const name = compactText(line?.source_material_name, "");
  const lotNo = compactText(line?.source_material_lot_no || line?.source_material_sub_batch_no, "");
  const traceParts = [code, name, lotNo].filter(Boolean);
  return traceParts.length ? traceParts.join(" · ") : "来源材料";
}

function returnableText(line) {
  return `${formatQty(line?.returnable_qty)} / ${formatWeight(line?.returnable_weight_kg)}`;
}

function returnedText(line) {
  return `${formatQty(line?.return_qty)} / ${formatWeight(line?.return_weight_kg)}`;
}

export function formatReturnDeliveryLineLabel(line) {
  if (!line) {
    return "请选择发货批次";
  }
  return [
    compactText(line.customer_name, "客户"),
    compactText(line.product_name, "产品"),
    sourceMaterialTrace(line),
    `可退 ${returnableText(line)}`
  ].join(" · ");
}

export function formatReturnReworkItemLabel(item) {
  if (!item) {
    return "请选择待返工退货明细";
  }
  return [
    compactText(item.product_name, "产品"),
    sourceMaterialTrace(item),
    `可返工 ${returnedText(item)}`
  ].join(" · ");
}

export function formatReturnTraceSummary(line) {
  if (!line) {
    return "请选择发货批次";
  }
  return [
    `客户：${compactText(line.customer_name, "客户")}`,
    `产品：${compactText(line.product_name, "产品")}`,
    `原材料库存批次：${sourceMaterialTrace(line)}`,
    `可退：${returnableText(line)}`
  ].join("；");
}
