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

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

  it("unreleases a released order with no execution evidence", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const draftOrder = { ...baseReleasedProductionOrder, status: "DRAFT" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // material requirements
    spies.select.mockReturnValueOnce([baseMaterialRequirement]);
    // cost summary - no actuals
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    // delete operations return
    spies.delete.mockReturnValue(undefined);
    // update order status
    spies.update.mockReturnValue(draftOrder);

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

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

  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 order is not in RELEASED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftProductionOrder);

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

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

  it("returns error when a work order has already started", 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]);
    // material requirements
    spies.select.mockReturnValueOnce([baseMaterialRequirement]);
    // 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("removes work orders and material requirements when unrelease succeeds", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const draftOrder = { ...baseReleasedProductionOrder, status: "DRAFT" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseReleasedProductionOrder);
    // work orders - all pending
    spies.select.mockReturnValueOnce([basePendingWorkOrder]);
    // material requirements
    spies.select.mockReturnValueOnce([]);
    // cost summary
    spies.select.mockReturnValueOnce(baseCollectingCostSummary);
    // delete operations
    spies.delete.mockReturnValue(undefined);
    // update order
    spies.update.mockReturnValue(draftOrder);

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

    expect(result.ok).toBe(true);
    expect(spies.delete).toHaveBeenCalled();
    expect(spies.update).toHaveBeenCalled();
  });
});
