import { describe, expect, it } from "vitest";
import { validateResult } from "@/workers/rpa/mothership";
import type { QuoteItem } from "@/modules/providers/quote-provider";
import { RpaError } from "@/modules/rpa/errors";

function buildTier(
  serviceLevel: QuoteItem["serviceLevel"],
  rateOption: QuoteItem["rateOption"],
  rawFreight = 100,
): QuoteItem {
  return {
    serviceLevel,
    rateOption,
    carrier: "Test",
    transitDays: "3-5",
    transitDescription: "3-5 business days",
    rawFreight,
    surcharges: 10,
    rawTotal: rawFreight + 10,
  };
}

describe("validateResult", () => {
  it("四档完整 → 通过", () => {
    const items = [
      buildTier("standard", "lowest"),
      buildTier("standard", "fastest"),
      buildTier("guaranteed", "lowest"),
      buildTier("guaranteed", "fastest"),
    ];
    expect(() => validateResult(items)).not.toThrow();
  });

  it("仅 standard/guaranteed lowest → fastest 复用后通过", () => {
    const items = [
      buildTier("standard", "lowest"),
      buildTier("guaranteed", "lowest"),
    ];
    expect(() => validateResult(items)).not.toThrow();
  });

  it("仅 1 档 → 通过（MotherShip 返回什么展示什么）", () => {
    const items = [buildTier("standard", "bestValue")];
    expect(() => validateResult(items)).not.toThrow();
  });

  it("缺 guaranteed 整档 → 通过", () => {
    const items = [
      buildTier("standard", "lowest"),
      buildTier("standard", "fastest"),
    ];
    expect(() => validateResult(items)).not.toThrow();
  });

  it("含 bestValue 扩展档 → 通过", () => {
    const items = [
      buildTier("standard", "lowest"),
      buildTier("standard", "fastest"),
      buildTier("standard", "bestValue", 120),
      buildTier("guaranteed", "lowest"),
      buildTier("guaranteed", "fastest"),
      buildTier("guaranteed", "bestValue", 130),
    ];
    expect(() => validateResult(items)).not.toThrow();
  });

  it("price=0 → RPA_DATA_INVALID", () => {
    const items = [
      buildTier("standard", "lowest", 0),
      buildTier("standard", "fastest"),
      buildTier("guaranteed", "lowest"),
      buildTier("guaranteed", "fastest"),
    ];
    expect(() => validateResult(items)).toThrow(RpaError);
  });

  it("price=-1 → RPA_DATA_INVALID", () => {
    const items = [
      buildTier("standard", "lowest", -1),
      buildTier("standard", "fastest"),
      buildTier("guaranteed", "lowest"),
      buildTier("guaranteed", "fastest"),
    ];
    expect(() => validateResult(items)).toThrow(RpaError);
  });
});
