import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { CompanyScopeRequiredError } from "../lib/errors.generated";
import { baseCompany, basePaymentTerm, draftPaymentTerm } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSalesPaymentTerms";

describe("listSalesPaymentTerms", () => {
  it("lists payment terms by company", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePaymentTerm, draftPaymentTerm]);

    const result = await run(db, { companyId: baseCompany.id });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(2);
  });

  it("filters payment terms by status when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePaymentTerm]);

    const result = await run(db, { companyId: baseCompany.id, status: "ACTIVE" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("throws when company scope is missing", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { companyId: "" });
    expectErr(result as never, CompanyScopeRequiredError);
  });
});
