import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { basePaymentTerm, baseScheduleLines } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getPurchasePaymentTerm";

describe("getPurchasePaymentTerm", () => {
  it("returns purchase payment term when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

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

    expect(purchasePaymentTerm).not.toBeNull();
    expect(purchasePaymentTerm).toMatchObject({
      id: basePaymentTerm.id,
      name: basePaymentTerm.name,
    });
  });

  it("returns schedule lines with the term", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

    const result = await run(db, { id: basePaymentTerm.id });
    const { purchasePaymentTerm } = expectOk<{
      purchasePaymentTerm: { scheduleLines: unknown[] };
    }>(result as never);

    expect(purchasePaymentTerm.scheduleLines).toEqual(baseScheduleLines);
  });

  it("returns null when purchase payment term does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

    expect(purchasePaymentTerm).toBeNull();
  });
});
