import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { SalesOrderIdRequiredError } from "../lib/errors.generated";
import { baseSalesInvoice, issuedSalesInvoice, confirmedSalesOrder } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listSalesInvoicesBySalesOrder";

describe("listSalesInvoicesBySalesOrder", () => {
  it("lists invoices under a sales order", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseSalesInvoice, issuedSalesInvoice]);

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

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

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

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

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

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

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