import { beforeEach, describe, expect, it, vi } from "vitest";
import {
  applyMarkup,
  applyMarkupToTier,
  getMarkupPercent,
} from "@/modules/pricing/engine";

vi.mock("@/lib/prisma", () => ({
  prisma: {
    markupConfig: {
      findFirst: vi.fn(),
    },
  },
}));

import { prisma } from "@/lib/prisma";

const mockedFindFirst = vi.mocked(prisma.markupConfig.findFirst);

describe("applyMarkup", () => {
  it("TC-103：raw_freight=320，surcharges=15，markup=10% → 32.00/367.00", () => {
    const rawTotal = 320 + 15;
    const result = applyMarkup(320, rawTotal, 10);
    expect(result.markupAmount).toBe(32.0);
    expect(result.finalTotal).toBe(367.0);
  });

  it("raw_freight=380，markup=10% → 38.00/418.00", () => {
    const result = applyMarkup(380, 380, 10);
    expect(result.markupAmount).toBe(38.0);
    expect(result.finalTotal).toBe(418.0);
  });

  it("surcharge=0 仅对 raw_freight 加价", () => {
    const result = applyMarkup(320, 320, 10);
    expect(result.markupAmount).toBe(32.0);
    expect(result.finalTotal).toBe(352.0);
  });

  it("0% 加价", () => {
    const result = applyMarkup(320, 335, 0);
    expect(result.markupAmount).toBe(0);
    expect(result.finalTotal).toBe(335);
  });

  it("30% 边界", () => {
    const result = applyMarkup(100, 100, 30);
    expect(result.markupAmount).toBe(30);
    expect(result.finalTotal).toBe(130);
  });

  it("0.01% 细粒度加价", () => {
    const result = applyMarkup(1000, 1000, 0.01);
    expect(result.markupAmount).toBe(0.1);
    expect(result.finalTotal).toBe(1000.1);
  });

  it("固定金额加价", () => {
    const result = applyMarkup(320, 335, {
      type: "fixed",
      percent: 0,
      fixedAmount: 50,
    });
    expect(result.markupAmount).toBe(50);
    expect(result.finalTotal).toBe(385);
  });
});

describe("applyMarkupToTier", () => {
  it("生成 breakdown 三项", () => {
    const tier = applyMarkupToTier(
      {
        service_level: "standard",
        rate_option: "lowest",
        carrier: "Mothership",
        transit_days: "5-7",
        transit_description: "最低价格",
        raw_freight: 320,
        surcharges: 15,
        raw_total: 335,
      },
      10,
    );
    expect(tier.breakdown).toHaveLength(3);
    expect(tier.final_total).toBe(367);
  });
});

describe("getMarkupPercent", () => {
  beforeEach(() => {
    mockedFindFirst.mockReset();
  });

  it("未配置 customer_id → 0.0", async () => {
    mockedFindFirst.mockResolvedValue(null);
    expect(await getMarkupPercent("CUST_UNKNOWN")).toBe(0);
  });

  it("已配置 10.0% → 10.0", async () => {
    mockedFindFirst.mockResolvedValue({
      markupType: "percent",
      markupPercent: 10.0,
      markupFixedAmount: null,
    } as never);
    expect(await getMarkupPercent("CUST_002")).toBe(10);
  });
});
