import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotClosableError,
  OpenWorkRemainsError,
  CostSummaryNotSettledError,
} from "../lib/errors.generated";
import {
  baseTechCompleteProductionOrder,
  baseCompletedProductionOrder,
  baseClosedProductionOrder,
  baseCompleteWorkOrder,
  baseCancelledWorkOrder,
  basePendingWorkOrder,
  baseSettledCostSummary,
  basePendingReviewCostSummary,
} from "../testing/fixtures";
import { run } from "./closeProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("closes a technically complete order with a settled cost summary", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const closed = { ...baseTechCompleteProductionOrder, status: "CLOSED" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // work orders - all complete or cancelled
    spies.select.mockReturnValueOnce([baseCompleteWorkOrder, baseCancelledWorkOrder]);
    // cost summary in SETTLED
    spies.select.mockReturnValueOnce({
      ...baseSettledCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });
    // update order status
    spies.update.mockReturnValue(closed);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("CLOSED");
    }
    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 technically complete", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompletedProductionOrder);

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

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

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

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

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

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

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

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

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

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

  it("blocks further execution commands after close", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseClosedProductionOrder);

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

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