import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { SalesInvoiceIdRequiredError } from "../lib/errors.generated";
import { baseCreditNote, issuedCreditNote, issuedSalesInvoice } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSalesCreditNotesByInvoice";

describe("listSalesCreditNotesByInvoice", () => {
  it("lists credit notes under an invoice", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCreditNote, issuedCreditNote]);

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

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

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

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

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

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

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