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 "./listPurchaseReceiptEvidenceForMatching";

describe("listPurchaseReceiptEvidenceForMatching", () => {
  it("lists posted purchase goods receipt evidence for matching", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const evidence = {
      purchaseOrderLineId: "po-line-1",
      inventoryExecutionLineId: "inventory-execution-line-1",
      inventoryExecutionId: "inventory-execution-1",
      quantity: "4",
      createdAt: new Date("2026-01-01T00:00:00Z"),
    };
    mock.enqueueResults([evidence]);

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

    expect(expectOk(result).receiptEvidence).toEqual([evidence]);
    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).toMatch(/"InventoryExecution"."sourceDocumentId" =/);
    expect(query.parameters).toContain("purchase-order-1");
  });

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

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

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