import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  MatchModeRequiredError,
  PaymentScheduleCalculationFailedError,
  PurchaseBillNotDraftError,
  PurchaseBillNotFoundError,
  PurchaseOrderCancelledError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk, mockInventoryQueries } from "../testing/commandTestUtils";
import {
  basePurchaseBill,
  basePurchaseBillLine,
  basePurchaseOrderLine,
  matchedPurchaseBill,
  orderedPurchaseOrder,
} from "../testing/fixtures";
import { run, type MatchPurchaseBillInput } from "./matchPurchaseBill";

const baseInventoryExecutionLine = {
  purchaseOrderLineId: basePurchaseOrderLine.id as string,
  inventoryExecutionLineId: "inventory-execution-line-1",
  inventoryExecutionId: "inventory-execution-1",
  quantity: basePurchaseBillLine.quantity as string,
  createdAt: new Date("2026-01-01T00:00:00Z"),
};

function runCommand(
  db: Transaction,
  input: MatchPurchaseBillInput,
  receiptEvidence = [baseInventoryExecutionLine],
) {
  return run(db, input, commandCtx, mockInventoryQueries({ receiptEvidence }));
}

describe("matchPurchaseBill", () => {
  it("matches a valid 2-way purchase bill", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    // no variance → update PurchaseBill then derive billingStatus
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" }); // update PurchaseBill
    spies.select
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine rows (per order)
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine (for order lines)
      .mockReturnValueOnce([matchedPurchaseBill]); // PurchaseBill (status=MATCHED)
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    }); // update PurchaseOrder

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "MATCHED", varianceReason: null }),
    );
  });

  it("matches a valid 3-way purchase bill when posted receipt quantity is sufficient", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]) // existing PurchaseBillLine rows for order quantity check
      .mockReturnValueOnce([]); // ThreeWayMatchEvent (existing matches)
    // ThreeWayMatchEvent insert
    spies.insert.mockReturnValueOnce(undefined);
    // no variance → update PurchaseBill then derive billingStatus
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "THREE_WAY" }); // update PurchaseBill
    spies.select
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine rows (per order)
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine (for order lines)
      .mockReturnValueOnce([matchedPurchaseBill]); // PurchaseBill (status=MATCHED)
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    }); // update PurchaseOrder

    const result = await runCommand(db, {
      id: basePurchaseBill.id,
      matchingMode: "THREE_WAY",
    });

    expect(expectOk(result).purchaseBill.matchingMode).toBe("THREE_WAY");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "MATCHED", varianceReason: null }),
    );
  });

  it("blocks a bill when 3-way quantity exceeds posted receipt quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const smallReceiptLine = { ...baseInventoryExecutionLine, quantity: "1" };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]) // existing PurchaseBillLine rows for order quantity check
      .mockReturnValueOnce([]); // ThreeWayMatchEvent (existing matches)
    // variance → no billed quantity updates
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "RECEIPT_QUANTITY_EXCEEDED",
    }); // update PurchaseBill

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "THREE_WAY" }, [
      smallReceiptLine,
    ]);

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "RECEIPT_QUANTITY_EXCEEDED" }),
    );
  });

  it("blocks a bill when cumulative billed quantity exceeds ordered quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const largeBillLine = { ...basePurchaseBillLine, quantity: "11" };
    const orderLine = { ...basePurchaseOrderLine, quantity: "10" };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([largeBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(orderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "ORDER_QUANTITY_EXCEEDED",
    });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "ORDER_QUANTITY_EXCEEDED" }),
    );
  });

  it("blocks a bill when prior matched bills plus current bill exceed ordered quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const existingMatchedBillLine = {
      ...basePurchaseBillLine,
      id: "existing-bill-line",
      purchaseBillId: matchedPurchaseBill.id,
      quantity: "8",
    };
    const orderLine = { ...basePurchaseOrderLine, quantity: "10" };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows (quantity 4)
      .mockReturnValueOnce(orderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([existingMatchedBillLine]) // existing PurchaseBillLine rows
      .mockReturnValueOnce([matchedPurchaseBill]); // matched PurchaseBill rows
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "ORDER_QUANTITY_EXCEEDED",
    });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "ORDER_QUANTITY_EXCEEDED" }),
    );
  });

  it("blocks a 3-way bill when prior matches leave insufficient received quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = { ...basePurchaseOrderLine, quantity: "20" };
    const postedReceiptLine = { ...baseInventoryExecutionLine, quantity: "10" };
    const existingMatch = {
      id: "match-existing",
      purchaseBillLineId: "existing-bill-line",
      inventoryExecutionLineId: postedReceiptLine.inventoryExecutionLineId,
      matchedQuantity: "8",
      matchedAt: new Date(),
      matchedBy: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows (quantity 4)
      .mockReturnValueOnce(orderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]) // existing PurchaseBillLine rows for order quantity check
      .mockReturnValueOnce([existingMatch]); // ThreeWayMatchEvent already consumed 8 of 10
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "RECEIPT_QUANTITY_EXCEEDED",
    });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "THREE_WAY" }, [
      postedReceiptLine,
    ]);

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "RECEIPT_QUANTITY_EXCEEDED" }),
    );
  });

  it("does not consume another receipt line from the same inventory execution", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const billLine = { ...basePurchaseBillLine, purchaseOrderLineId: "po-line-2" };
    const orderLine = { ...basePurchaseOrderLine, id: "po-line-2", quantity: "20" };
    const otherReceiptLine = {
      ...baseInventoryExecutionLine,
      purchaseOrderLineId: "po-line-1",
      inventoryExecutionLineId: "inventory-execution-line-1",
      quantity: "4",
    };
    const targetReceiptLine = {
      ...baseInventoryExecutionLine,
      purchaseOrderLineId: "po-line-2",
      inventoryExecutionLineId: "inventory-execution-line-2",
      quantity: "4",
    };
    const existingMatchOnOtherLine = {
      id: "match-existing",
      purchaseBillLineId: "existing-bill-line",
      inventoryExecutionLineId: otherReceiptLine.inventoryExecutionLineId,
      matchedQuantity: "4",
      matchedAt: new Date(),
      matchedBy: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([billLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(orderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]) // existing PurchaseBillLine rows for order quantity check
      .mockReturnValueOnce([existingMatchOnOtherLine]); // same execution, different receipt line
    spies.insert.mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "THREE_WAY" });
    spies.select
      .mockReturnValueOnce([orderLine])
      .mockReturnValueOnce([billLine])
      .mockReturnValueOnce([matchedPurchaseBill]);
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "THREE_WAY" }, [
      otherReceiptLine,
      targetReceiptLine,
    ]);

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");
    expect(spies.values).toHaveBeenCalledWith(
      expect.arrayContaining([
        expect.objectContaining({
          purchaseBillLineId: billLine.id,
          inventoryExecutionLineId: targetReceiptLine.inventoryExecutionLineId,
          matchedQuantity: billLine.quantity,
        }),
      ]),
    );
  });

  it("blocks a bill when price variance exceeds tolerance", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const highPriceBillLine = { ...basePurchaseBillLine, billedUnitPrice: 120 };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([highPriceBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    // variance → no billed quantity updates
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "PRICE_VARIANCE_EXCEEDED",
    }); // update PurchaseBill

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "PRICE_VARIANCE_EXCEEDED" }),
    );
  });

  it("records matching mode on the bill", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    // no variance → update PurchaseBill then derive billingStatus
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" }); // update PurchaseBill
    spies.select
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine rows (per order)
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine (for order lines)
      .mockReturnValueOnce([matchedPurchaseBill]); // PurchaseBill (status=MATCHED)
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    }); // update PurchaseOrder

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.matchingMode).toBe("TWO_WAY");
  });

  it("derives purchase-order billing status when the bill is matched", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    // no variance → update PurchaseBill then derive billingStatus
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" }); // update PurchaseBill
    spies.select
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine rows (per order)
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine (for order lines)
      .mockReturnValueOnce([matchedPurchaseBill]); // PurchaseBill (status=MATCHED)
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    }); // update PurchaseOrder

    await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    // billingStatus is derived from PurchaseBillLine + MATCHED bills
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ billingStatus: expect.any(String) as string }),
    );
  });

  it("matches a purchase bill with PO-unlinked lines (skip PO variance checks, include in amount)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const unlinkedBillLine = { ...basePurchaseBillLine, purchaseOrderLineId: null };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([unlinkedBillLine]) // PurchaseBillLine rows (PO-unlinked)
      .mockReturnValueOnce([]);
    // No PO line/order lookups for unlinked lines
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" }); // update PurchaseBill

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");
  });

  it("creates ThreeWayMatchEvent records for bill-line-to-receipt-line correspondence", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]) // existing PurchaseBillLine rows for order quantity check
      .mockReturnValueOnce([]); // ThreeWayMatchEvent (existing matches)
    // ThreeWayMatchEvent insert (no return value needed)
    spies.insert.mockReturnValueOnce(undefined);
    // no variance → update PurchaseBill then derive billingStatus
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "THREE_WAY" }); // update PurchaseBill
    spies.select
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine rows (per order)
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine (for order lines)
      .mockReturnValueOnce([matchedPurchaseBill]); // PurchaseBill (status=MATCHED)
    spies.update.mockReturnValueOnce({
      ...orderedPurchaseOrder,
      billingStatus: "PARTIALLY_BILLED",
    }); // update PurchaseOrder

    const result = await runCommand(db, {
      id: basePurchaseBill.id,
      matchingMode: "THREE_WAY",
    });

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");

    // Verify ThreeWayMatchEvent was inserted with correct bill-line-to-receipt-line mapping
    expect(spies.values).toHaveBeenCalledWith(
      expect.arrayContaining([
        expect.objectContaining({
          purchaseBillLineId: basePurchaseBillLine.id,
          inventoryExecutionLineId: baseInventoryExecutionLine.inventoryExecutionLineId,
          matchedQuantity: basePurchaseBillLine.quantity,
        }),
      ]),
    );
  });

  it("returns error when purchase bill does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    expectErr(
      await runCommand(db, { id: "missing-bill", matchingMode: "TWO_WAY" }),
      PurchaseBillNotFoundError,
    );
  });

  it("returns error when purchase bill is not draft", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(matchedPurchaseBill);
    expectErr(
      await runCommand(db, { id: matchedPurchaseBill.id, matchingMode: "TWO_WAY" }),
      PurchaseBillNotDraftError,
    );
  });

  it("returns error when matching mode is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePurchaseBill);
    expectErr(
      await runCommand(db, { id: basePurchaseBill.id, matchingMode: undefined as never }),
      MatchModeRequiredError,
    );
  });

  it("returns error when a referenced purchase order is cancelled", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce({ ...orderedPurchaseOrder, orderStatus: "CANCELLED" }); // PurchaseOrder (cancelled)
    expectErr(
      await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" }),
      PurchaseOrderCancelledError,
    );
  });

  it("returns error when payment schedule calculation fails", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const invalidScheduleBill = {
      ...basePurchaseBill,
      paymentTermSnapshotLines: [],
    };
    spies.select
      .mockReturnValueOnce(invalidScheduleBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine (getOrderLine per bill line)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder (per bill line)
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    expectErr(
      await runCommand(db, { id: invalidScheduleBill.id, matchingMode: "TWO_WAY" }),
      PaymentScheduleCalculationFailedError,
    );
  });

  it("detects price variance when ordered unit price is zero and billed is positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const zeroUnitPriceOrderLine = { ...basePurchaseOrderLine, unitPrice: "0" };
    const positiveBilledBillLine = { ...basePurchaseBillLine, billedUnitPrice: "10" };
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([positiveBilledBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(zeroUnitPriceOrderLine) // PurchaseOrderLine (getOrderLine)
      .mockReturnValueOnce(orderedPurchaseOrder) // PurchaseOrder
      .mockReturnValueOnce([]); // existing PurchaseBillLine rows for order quantity check
    spies.update.mockReturnValueOnce({
      ...basePurchaseBill,
      status: "BLOCKED",
      varianceReason: "PRICE_VARIANCE_EXCEEDED",
    });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("BLOCKED");
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "BLOCKED", varianceReason: "PRICE_VARIANCE_EXCEEDED" }),
    );
  });

  it("skips bill lines when resolved order line is not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // A bill line references a PO line but getOrderLine returns undefined
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(undefined); // getOrderLine returns undefined (no order line found)
    // No PO lookup since orderLine is null → continue
    // calculateDueSchedule then update
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");
  });

  it("skips bill lines when purchase order for the order line is not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(basePurchaseBill) // PurchaseBill
      .mockReturnValueOnce([basePurchaseBillLine]) // PurchaseBillLine rows
      .mockReturnValueOnce(basePurchaseOrderLine) // PurchaseOrderLine found
      .mockReturnValueOnce(undefined); // PurchaseOrder not found → continue
    // calculateDueSchedule then update
    spies.update.mockReturnValueOnce({ ...matchedPurchaseBill, matchingMode: "TWO_WAY" });

    const result = await runCommand(db, { id: basePurchaseBill.id, matchingMode: "TWO_WAY" });

    expect(expectOk(result).purchaseBill.status).toBe("MATCHED");
  });
});
