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

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

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

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

  it("returns inactive payment term when requested directly", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(inactivePaymentTerm);

    const result = await run(db, { id: inactivePaymentTerm.id });
    const { salesPaymentTerm } = expectOk<{ salesPaymentTerm: { status: string } }>(
      result as never,
    );

    expect(salesPaymentTerm.status).toBe("INACTIVE");
  });

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

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

    expect(salesPaymentTerm).toBeNull();
  });
});
