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 {
  basePurchaseBill,
  basePurchaseOrder,
  orderedPurchaseOrder,
  postedGoodsReceipt,
  submittedPurchaseOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelPurchaseOrder";

describe("cancelPurchaseOrder", () => {
  it("cancels a draft purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...basePurchaseOrder, status: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(basePurchaseOrder)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce([]);
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).purchaseOrder.status).toBe("CANCELLED");
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "CANCELLED" }));
  });

  it("cancels a submitted purchase order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...submittedPurchaseOrder, status: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(submittedPurchaseOrder)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce([]);
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).purchaseOrder.status).toBe("CANCELLED");
  });

  it("cancels an ordered purchase order with no receipts or matched bills", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const unrelatedMatchedBill = {
      ...basePurchaseBill,
      id: "purchase-bill-unrelated",
      status: "MATCHED",
      lines: JSON.stringify([{ purchaseOrderLineId: "other-line", quantity: 1 }]),
    };
    const cancelled = { ...orderedPurchaseOrder, status: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce([unrelatedMatchedBill]);
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).purchaseOrder.status).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, status: "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>();
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder)
      .mockReturnValueOnce({ ...postedGoodsReceipt, purchaseOrderId: orderedPurchaseOrder.id });

    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 matchedBill = {
      ...basePurchaseBill,
      status: "MATCHED",
      lines: JSON.stringify([
        {
          purchaseOrderLineId: "po-line-1",
          quantity: 1,
        },
      ]),
    };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce([matchedBill]);

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

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