import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotCompletableError,
  OpenWorkOrderRemainsError,
  FinalOutputRequiredError,
  FinalReceiptRequiredError,
} from "../lib/errors.generated";
import {
  baseInProgressProductionOrder,
  baseDraftProductionOrder,
  baseCompleteWorkOrder,
  baseCancelledWorkOrder,
  baseInProgressWorkOrder,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { run } from "./completeProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("completes an in-progress order after all required work orders finish", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const completed = { ...baseInProgressProductionOrder, status: "COMPLETED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);
    // work orders - all complete or cancelled
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder, baseCancelledWorkOrder]);
    // cost summary with actual costs
    spies.select.mockReturnValueOnce({
      ...baseCollectingCostSummary,
      productionOrderId: baseInProgressProductionOrder.id,
      actualMaterialCost: 500,
    });
    // update order status
    spies.update.mockReturnValue(completed);

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

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

  it("returns error when required work orders remain open", async () => {
    const { db, spies } = createMockDb<Transaction>();

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

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

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

  it("returns error when final output reporting is incomplete", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const completedWithZero = { ...baseCompleteWorkOrder, completedQuantity: 0 };

    // order lookup
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);
    // work orders - all cancelled (no completed output)
    spies.select.mockReturnValueOnce([baseCancelledWorkOrder, completedWithZero]);

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

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

  it("returns error when required receipt handoff evidence is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();

    // order lookup
    spies.select.mockReturnValueOnce(baseInProgressProductionOrder);
    // work orders - all complete with output
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder]);
    // cost summary with no actual costs
    spies.select.mockReturnValueOnce({
      ...baseCollectingCostSummary,
      productionOrderId: baseInProgressProductionOrder.id,
      actualMaterialCost: 0,
    });

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

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