import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  OpenChangeOrderExistsError,
  PurchaseOrderAlreadyFulfilledError,
  PurchaseOrderNotCancellableError,
  PurchaseOrderNotFoundError,
} from "../lib/errors.generated";
import {
  basePurchaseBill,
  basePurchaseOrderLine,
  basePurchaseOrder,
  orderedPurchaseOrder,
  baseGoodsReceiptLine,
  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, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(basePurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce([]); // selectFrom PurchaseBill (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).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(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce([]); // selectFrom PurchaseBill (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).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 unrelatedBillLine = {
      id: "bl-1",
      purchaseBillId: "purchase-bill-unrelated",
      purchaseOrderLineId: "other-line",
      quantity: 1,
    };
    const unrelatedMatchedBill = {
      ...basePurchaseBill,
      id: "purchase-bill-unrelated",
      status: "MATCHED",
    };
    const cancelled = { ...orderedPurchaseOrder, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(undefined) // selectFrom GoodsReceiptLine join GoodsReceipt (executeTakeFirst)
      .mockReturnValueOnce([unrelatedMatchedBill]) // selectFrom PurchaseBill (execute → array)
      .mockReturnValueOnce([unrelatedBillLine]); // selectFrom PurchaseBillLine for unrelatedMatchedBill (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

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

    expect(expectOk(result).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(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(baseGoodsReceiptLine); // selectFrom GoodsReceiptLine join GoodsReceipt (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 matchedBill = {
      ...basePurchaseBill,
      status: "MATCHED",
    };
    const billLine = {
      id: "bl-1",
      purchaseBillId: matchedBill.id,
      purchaseOrderLineId: poLine.id,
      quantity: 1,
    };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — not found)
      .mockReturnValueOnce([poLine]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce(undefined) // selectFrom GoodsReceiptLine join GoodsReceipt (executeTakeFirst — not found)
      .mockReturnValueOnce([matchedBill]) // selectFrom PurchaseBill (execute → array)
      .mockReturnValueOnce([billLine]); // selectFrom PurchaseBillLine (execute → array)

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

    expectErr(result, PurchaseOrderAlreadyFulfilledError);
  });

  it("returns error when an open change order exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const openCO = {
      id: "co-1",
      purchaseOrderId: orderedPurchaseOrder.id,
      changeOrderStatus: "DRAFT",
    };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(openCO); // selectFrom PurchaseChangeOrder (executeTakeFirst — found)

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

    expectErr(result, OpenChangeOrderExistsError);
  });

  it("cancels when all change orders are APPLIED or CANCELLED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...orderedPurchaseOrder, orderStatus: "CANCELLED" };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([]) // selectFrom PurchaseOrderLine (execute → array)
      .mockReturnValueOnce([]); // selectFrom PurchaseBill (execute → array)
    spies.update.mockReturnValueOnce(cancelled);

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

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

  it("returns error when a SUPERSEDED line has posted receipts", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const supersededLine = {
      ...basePurchaseOrderLine,
      purchaseOrderId: orderedPurchaseOrder.id,
      lineStatus: "SUPERSEDED",
      rootLineId: null,
      supersededByLineId: "po-line-active",
    };
    spies.select
      .mockReturnValueOnce(orderedPurchaseOrder) // selectOne PurchaseOrder
      .mockReturnValueOnce(undefined) // selectFrom PurchaseChangeOrder (executeTakeFirst — no open CO)
      .mockReturnValueOnce([supersededLine]) // selectFrom PurchaseOrderLine (execute → array, includes SUPERSEDED)
      .mockReturnValueOnce(baseGoodsReceiptLine); // selectFrom GoodsReceiptLine join GoodsReceipt (executeTakeFirst — found)

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

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