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

describe("listSalesInvoicesBySalesOrder", () => {
  it("lists invoices under a sales order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesInvoice, issuedSalesInvoice]);

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

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

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

    const result = await run(mock.db, { salesOrderId: confirmedSalesOrder.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 sales-order id is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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