import { describe, expect, it } from "vitest";
import {
  applyMarkup,
  applyMarkupToQuotes,
  type RawQuoteTier,
} from "@/modules/pricing/engine";

const RAW_TIERS: RawQuoteTier[] = [
  {
    service_level: "standard",
    rate_option: "lowest",
    carrier: "Mothership",
    transit_days: "5-7",
    transit_description: "最低价格",
    raw_freight: 320,
    surcharges: 15,
    raw_total: 335,
  },
  {
    service_level: "standard",
    rate_option: "fastest",
    carrier: "Mothership",
    transit_days: "3-4",
    transit_description: "最快",
    raw_freight: 365,
    surcharges: 0,
    raw_total: 365,
  },
  {
    service_level: "guaranteed",
    rate_option: "lowest",
    carrier: "Mothership",
    transit_days: "4-5",
    transit_description: "保价最低",
    raw_freight: 380,
    surcharges: 0,
    raw_total: 380,
  },
  {
    service_level: "guaranteed",
    rate_option: "fastest",
    carrier: "Mothership",
    transit_days: "2-3",
    transit_description: "保价最快",
    raw_freight: 410,
    surcharges: 0,
    raw_total: 410,
  },
];

describe("TC-403 加价可复算（task-114）", () => {
  it("从 DB raw_freight + markup 重算 final_total 误差 ≤0.01", () => {
    const markupPercent = 10;
    const marked = applyMarkupToQuotes(RAW_TIERS, markupPercent);

    for (let i = 0; i < RAW_TIERS.length; i++) {
      const raw = RAW_TIERS[i];
      const expected = applyMarkup(
        raw.raw_freight,
        raw.raw_total,
        markupPercent,
      );
      const actual = marked[i];
      expect(Math.abs(actual.final_total - expected.finalTotal)).toBeLessThanOrEqual(
        0.01,
      );
      expect(Math.abs(actual.markup_amount - expected.markupAmount)).toBeLessThanOrEqual(
        0.01,
      );
    }
  });

  it("TC-103 精确到分：markup_amount=32.00 final_total=367.00", () => {
    const result = applyMarkup(320, 335, 10);
    expect(result.markupAmount).toBe(32);
    expect(result.finalTotal).toBe(367);
  });
});
