import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { basePriceList, basePriceRule, higherBreakPriceRule } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getPurchasePriceList";

describe("getPurchasePriceList", () => {
  it("returns purchase price list when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePriceList);
    spies.select.mockReturnValueOnce([basePriceRule]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePriceList);
    spies.select.mockReturnValueOnce([basePriceRule, higherBreakPriceRule]);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

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