import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { basePriceList, basePriceRule, higherBreakPriceRule } from "../testing/fixtures";
import { run } from "./getPurchasePriceList";

describe("getPurchasePriceList", () => {
  it("returns purchase price list when found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [basePriceRule]);

    const result = await run(mock.db, { id: basePriceList.id });
    const { purchasePriceList } = expectOk<{ purchasePriceList: unknown }>(result as never);

    expect(purchasePriceList).not.toBeNull();
    expect(purchasePriceList).toMatchObject({
      id: basePriceList.id,
      name: basePriceList.name,
    });
  });

  it("returns embedded purchase price rules with the list", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePriceList], [basePriceRule, higherBreakPriceRule]);

    const result = await run(mock.db, { id: basePriceList.id });
    const { purchasePriceList } = expectOk<{
      purchasePriceList: { rules: unknown[] };
    }>(result as never);

    expect(purchasePriceList.rules).toHaveLength(2);
    expect(purchasePriceList.rules).toContainEqual(basePriceRule);
    expect(purchasePriceList.rules).toContainEqual(higherBreakPriceRule);
  });

  it("returns null when purchase price list does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent-id" });
    const { purchasePriceList } = expectOk<{ purchasePriceList: null }>(result as never);

    expect(purchasePriceList).toBeNull();
  });
});
