import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { SalesInvoiceIdRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseCreditNote, issuedCreditNote, issuedSalesInvoice } from "../testing/fixtures";
import { run } from "./listSalesCreditNotesByInvoice";

describe("listSalesCreditNotesByInvoice", () => {
  it("lists credit notes under an invoice", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseCreditNote, issuedCreditNote]);

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

    expect(items).toHaveLength(2);
    expect(mock.selects[0].parameters).toContain(issuedSalesInvoice.id);
    expect(mock.selects[0].sql).toMatch(/"salesInvoiceId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"creditDate" desc/i);
  });

  it("filters credit notes by status when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([issuedCreditNote]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("ISSUED");
    expect(mock.selects[0].sql).toMatch(/"status"/);
  });

  it("throws when invoice id is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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