import { beforeEach, describe, expect, it } from "vitest";
import { validateProbeItems } from "@/lib/rpa/probe-validation";
import { executeProbeQuote } from "@/lib/rpa/run-probe";
import type { QuoteItem } from "@/modules/providers/quote-provider";

function fourTiers(): QuoteItem[] {
  return [
    {
      serviceLevel: "standard",
      rateOption: "lowest",
      carrier: "M",
      transitDays: "5",
      transitDescription: "最低",
      rawFreight: 320,
      surcharges: 0,
      rawTotal: 320,
    },
    {
      serviceLevel: "standard",
      rateOption: "fastest",
      carrier: "M",
      transitDays: "3",
      transitDescription: "最快",
      rawFreight: 365,
      surcharges: 0,
      rawTotal: 365,
    },
    {
      serviceLevel: "guaranteed",
      rateOption: "lowest",
      carrier: "M",
      transitDays: "4",
      transitDescription: "保价最低",
      rawFreight: 380,
      surcharges: 0,
      rawTotal: 380,
    },
    {
      serviceLevel: "guaranteed",
      rateOption: "fastest",
      carrier: "M",
      transitDays: "2",
      transitDescription: "保价最快",
      rawFreight: 410,
      surcharges: 0,
      rawTotal: 410,
    },
  ];
}

describe("TC-601 probe 校验（task-133）", () => {
  it("validateProbeItems：4 档通过", () => {
    expect(validateProbeItems(fourTiers())).toEqual({ ok: true });
  });

  it("validateProbeItems：仅 2 档 lowest → 通过（fastest 复用）", () => {
    const twoLowest = [
      fourTiers()[0],
      fourTiers()[2],
    ];
    expect(validateProbeItems(twoLowest)).toEqual({ ok: true });
  });

  it("validateProbeItems：仅 1 档 → 失败", () => {
    const result = validateProbeItems([fourTiers()[0]]);
    expect(result.ok).toBe(false);
  });

  it("mock 模式 executeProbeQuote → items.length===4", async () => {
    process.env.RPA_MOCK_MODE = "true";
    const result = await executeProbeQuote();
    expect(result.items).toHaveLength(4);
    expect(validateProbeItems(result.items)).toEqual({ ok: true });
    result.items.forEach((item) => {
      expect(item.rawFreight).toBeGreaterThan(0);
      expect(item.transitDescription).toBeTruthy();
    });
  });
});

describe("probe 3/3 模拟（task-133）", () => {
  beforeEach(() => {
    process.env.RPA_MOCK_MODE = "true";
  });

  it("连续 3 次 mock probe 均四档齐全", async () => {
    for (let i = 0; i < 3; i++) {
      const result = await executeProbeQuote();
      expect(result.items.length).toBe(4);
      expect(validateProbeItems(result.items).ok).toBe(true);
    }
  });
});
