import type { QuoteItem } from "@/modules/providers/quote-provider";
import type { RawQuoteTier } from "@/modules/pricing/engine";
import type { Priority1QuoteLine } from "@/workers/rpa/priority1/quote-extract";

const RATE_BY_RANK: Array<QuoteItem["rateOption"]> = [
  "lowest",
  "fastest",
  "bestValue",
  "lowest",
];

/** Priority1 承运商列表 → 系统报价格式（不要求四档齐全） */
export function priority1LinesToQuoteItems(
  lines: Priority1QuoteLine[],
): QuoteItem[] {
  return lines.map((line, idx) => {
    const total = line.totalUsd;
    return {
      serviceLevel: line.serviceLevel.toLowerCase().includes("expedited")
        ? "guaranteed"
        : "standard",
      rateOption: RATE_BY_RANK[idx] ?? "lowest",
      carrier: line.carrier || line.carrierCode || "Unknown",
      transitDays: String(line.transitDays || "—"),
      transitDescription: line.deliveryDate
        ? `预计送达 ${line.deliveryDate}`
        : `${line.transitDays} 天`,
      rawFreight: total,
      surcharges: 0,
      rawTotal: total,
    };
  });
}

export function priority1LinesToRawTiers(lines: Priority1QuoteLine[]): RawQuoteTier[] {
  return priority1LinesToQuoteItems(lines).map((item) => ({
    service_level: item.serviceLevel,
    rate_option: item.rateOption,
    carrier: item.carrier,
    transit_days: item.transitDays,
    transit_description: item.transitDescription,
    raw_freight: item.rawFreight,
    surcharges: item.surcharges,
    raw_total: item.rawTotal,
  }));
}
