import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotCancellableError,
  ExecutionAlreadyStartedError,
  InventoryHandoffExistsError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseInProgressProductionOrder,
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { run } from "./cancelProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

describe("cancelProductionOrder", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing:cancelProductionOrder"],
  };

  it("cancels a draft production order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...baseDraftProductionOrder, status: "CANCELLED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);
    // update order status
    spies.update.mockReturnValue(cancelled);

    const result = await run(db, { id: baseDraftProductionOrder.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("CANCELLED");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("cancels a released order before execution starts", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...baseReleasedProductionOrder, status: "CANCELLED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // cost summary - no actuals
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    // cascade cancel work orders
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(cancelled);

    const result = await run(db, { id: baseReleasedProductionOrder.id }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("CANCELLED");
    }
  });

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

    const result = await run(db, { id: "nonexistent" }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductionOrderNotFoundError);
    }
  });

  it("returns error when the status does not allow cancellation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);

    const result = await run(db, { id: baseInProgressProductionOrder.id }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductionOrderNotCancellableError);
    }
  });

  it("returns error when execution evidence already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - one in progress
    spies.select.mockReturnValueOnce([baseInProgressWorkOrder]);

    const result = await run(db, { id: baseReleasedProductionOrder.id }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ExecutionAlreadyStartedError);
    }
  });

  it("returns error when inventory handoff evidence already exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const costSummaryWithActuals = {
      ...baseCollectingCostSummary,
      actualMaterialCost: 500,
    };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // cost summary with actual costs
    spies.select.mockReturnValueOnce(costSummaryWithActuals);

    const result = await run(db, { id: baseReleasedProductionOrder.id }, ctx);

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InventoryHandoffExistsError);
    }
  });

  it("cascades cancellation to pending work orders", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...baseReleasedProductionOrder, status: "CANCELLED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // cost summary - no actuals
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    // cascade cancel work orders (first update call)
    spies.update.mockReturnValueOnce(undefined);
    // update order status (second update call)
    spies.update.mockReturnValue(cancelled);

    const result = await run(db, { id: baseReleasedProductionOrder.id }, ctx);

    expect(result.ok).toBe(true);
    // update should be called at least twice: once for work orders, once for order
    expect(spies.update).toHaveBeenCalled();
  });
});
