import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotTechnicallyCompletableError,
  ExecutionExceptionRemainsError,
  PendingMaterialIssueRequestsError,
  CostSummaryNotReadyError,
} from "../lib/errors.generated";
import {
  baseCompletedProductionOrder,
  baseInProgressProductionOrder,
  baseCompleteWorkOrder,
  baseCancelledWorkOrder,
  baseInProgressWorkOrder,
  basePausedWorkOrder,
  basePendingWorkOrder,
  baseCollectingCostSummary,
  basePendingReviewCostSummary,
} from "../testing/fixtures";
import { run } from "./technicallyCompleteProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("technically completes a completed order and opens variance review", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const techComplete = {
      ...baseCompletedProductionOrder,
      status: "TECHNICALLY_COMPLETE" as const,
    };

    // order lookup
    spies.select.mockReturnValueOnce(baseCompletedProductionOrder);
    // work orders - all complete or cancelled
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder, baseCancelledWorkOrder]);
    // cost summary in COLLECTING
    spies.select.mockReturnValueOnce({
      ...baseCollectingCostSummary,
      productionOrderId: baseCompletedProductionOrder.id,
    });
    // update cost summary
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(techComplete);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("TECHNICALLY_COMPLETE");
    }
    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 COMPLETED", 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(ProductionOrderNotTechnicallyCompletableError);
    }
  });

  it("returns error when unresolved execution exceptions remain", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

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

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

  it("returns error when pending material issue requests or unresolved backflush intents remain", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup
    spies.select.mockReturnValueOnce(baseCompletedProductionOrder);
    // work orders - one still pending
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder, basePendingWorkOrder]);

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

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

  it("returns error when the linked cost summary is not ready for review", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup
    spies.select.mockReturnValueOnce(baseCompletedProductionOrder);
    // work orders - all complete
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder]);
    // cost summary already in PENDING_VARIANCE_REVIEW (not COLLECTING)
    spies.select.mockReturnValueOnce({
      ...basePendingReviewCostSummary,
      productionOrderId: baseCompletedProductionOrder.id,
    });

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

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

  it("blocks further shop-floor reporting after technical completion", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup - already paused work order still open
    spies.select.mockReturnValueOnce(baseCompletedProductionOrder);
    // work orders - one paused (execution exception)
    spies.select.mockReturnValueOnce([basePausedWorkOrder]);

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

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