import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } 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 { db, spies } = createMockDb<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"),
    };
    spies.select.mockReturnValueOnce([evidence]);

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

    expect(expectOk(result).receiptEvidence).toEqual([evidence]);
    expect(spies.where).toHaveBeenCalledWith("InventoryExecutionLine.sourceLineId", "in", [
      "po-line-1",
    ]);
    expect(spies.where).toHaveBeenCalledWith(
      "InventoryExecution.sourceDocumentType",
      "=",
      "PURCHASE_ORDER",
    );
    expect(spies.where).toHaveBeenCalledWith(
      "InventoryExecution.sourceDocumentId",
      "=",
      "purchase-order-1",
    );
  });

  it("returns empty evidence without querying when no purchase order lines are provided", async () => {
    const { db, spies } = createMockDb<DB>();

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

    expect(expectOk(result).receiptEvidence).toEqual([]);
    expect(spies.select).not.toHaveBeenCalled();
  });
});
