import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PurchaseOrderAlreadyFulfilledError,
  PurchaseOrderNotCancellableError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";
import {
  commandCtx,
  expectErr,
  mockInventoryCommands,
  mockInventoryQueries,
} from "../testing/commandTestUtils";
import {
  basePurchaseBillLine,
  basePurchaseOrderLine,
  basePurchaseOrder,
  orderedPurchaseOrder,
  baseInventoryReceiptEvidence,
  submittedPurchaseOrder,
} from "../testing/fixtures";
import { run as runCommand } from "./cancelPurchaseOrder";

function run(
  db: Parameters<typeof runCommand>[0],
  input: Parameters<typeof runCommand>[1],
  ctx: Parameters<typeof runCommand>[2],
  inventoryCommands: Parameters<typeof runCommand>[3] = mockInventoryCommands(),
  inventoryQueries: Parameters<typeof runCommand>[4] = mockInventoryQueries(),
) {
  return runCommand(db, input, ctx, inventoryCommands, inventoryQueries);
}

describe("cancelPurchaseOrder", () => {
  it("cancels a draft purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...basePurchaseOrder, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce([]); // selectFrom PurchaseOrderLine (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

    const result = await run(db, { id: basePurchaseOrder.id }, commandCtx);

    expect(result.ok).toBe(true);
    if (!result.ok) throw result.error;
    expect(result.value.purchaseOrder.orderStatus).toBe("CANCELLED");
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ orderStatus: "CANCELLED" }));
  });

  it("cancels a submitted purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...submittedPurchaseOrder, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce([]); // selectFrom PurchaseOrderLine (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

    const result = await run(db, { id: submittedPurchaseOrder.id }, commandCtx);

    expect(result.ok).toBe(true);
    if (!result.ok) throw result.error;
    expect(result.value.purchaseOrder.orderStatus).toBe("CANCELLED");
  });

  it("cancels an ordered purchase order with no receipts or matched bills", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const poLine = { ...basePurchaseOrderLine, purchaseOrderId: orderedPurchaseOrder.id };
    const cancelled = { ...orderedPurchaseOrder, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(undefined) // inventory receipt evidence (executeTakeFirst — not found)
      .mockReturnValueOnce(undefined); // selectFrom PurchaseBillLine join PurchaseBill (executeTakeFirst — not found)
    spies.update.mockReturnValueOnce(cancelled);

    const result = await run(db, { id: orderedPurchaseOrder.id }, commandCtx);

    expect(result.ok).toBe(true);
    if (!result.ok) throw result.error;
    expect(result.value.purchaseOrder.orderStatus).toBe("CANCELLED");
  });

  it("returns error when purchase order does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing-order" }, commandCtx);

    expectErr(result, PurchaseOrderNotFoundError);
  });

  it("returns error when purchase order status does not allow cancellation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...orderedPurchaseOrder, orderStatus: "CLOSED" });

    const result = await run(db, { id: orderedPurchaseOrder.id }, commandCtx);

    expectErr(result, PurchaseOrderNotCancellableError);
  });

  it("returns error when a posted receipt already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const poLine = { ...basePurchaseOrderLine, purchaseOrderId: orderedPurchaseOrder.id };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(baseInventoryReceiptEvidence); // inventory receipt evidence (executeTakeFirst — found)

    const result = await run(db, { id: orderedPurchaseOrder.id }, commandCtx);

    expectErr(result, PurchaseOrderAlreadyFulfilledError);
  });

  it("returns error when a matched bill already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const poLine = { ...basePurchaseOrderLine, purchaseOrderId: orderedPurchaseOrder.id };
    const matchedBillLine = {
      ...basePurchaseBillLine,
      purchaseOrderLineId: poLine.id,
    };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(undefined) // inventory receipt evidence (executeTakeFirst — not found)
      .mockReturnValueOnce(matchedBillLine); // selectFrom PurchaseBillLine join PurchaseBill (executeTakeFirst — found)

    const result = await run(db, { id: orderedPurchaseOrder.id }, commandCtx);

    expectErr(result, PurchaseOrderAlreadyFulfilledError);
  });
});
