import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./listPurchaseReceiptQuantitiesForMatching";

describe("listPurchaseReceiptQuantitiesForMatching", () => {
  it("lists posted purchase goods receipt quantities by purchase order line", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([
      { purchaseOrderLineId: "po-line-1", quantity: "1.5" },
      { purchaseOrderLineId: "po-line-1", quantity: "2.5" },
    ]);

    const result = await run(mock.db, {
      purchaseOrderLineIds: ["po-line-1"],
    });

    expect(expectOk(result).receiptQuantities).toEqual([
      { purchaseOrderLineId: "po-line-1", receivedQuantity: "4" },
    ]);
    const query = mock.selects[0];
    expect(query.sql).toMatch(/"InventoryExecutionLine"."sourceLineId" in/);
    expect(query.parameters).toContain("po-line-1");
    expect(query.sql).toMatch(/"InventoryExecution"."sourceDocumentType" =/);
    expect(query.parameters).toContain("PURCHASE_ORDER");
    expect(query.sql).not.toMatch(/group by/i);
    expect(query.sql).not.toMatch(/sum/i);
  });

  it("returns empty quantities without querying when no purchase order lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await run(mock.db, { purchaseOrderLineIds: [] });

    expect(expectOk(result).receiptQuantities).toEqual([]);
    expect(mock.selects).toHaveLength(0);
  });
});
