import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotReopenableError,
  ReopenReasonRequiredError,
  CostSummaryNotReopenableError,
  OrderAlreadyClosedError,
} from "../lib/errors.generated";
import {
  baseTechCompleteProductionOrder,
  baseCompletedProductionOrder,
  baseClosedProductionOrder,
  basePendingReviewCostSummary,
  baseReviewedCostSummary,
  baseSettledCostSummary,
} from "../testing/fixtures";
import { run } from "./reopenProductionOrder";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const validInput = {
    id: baseTechCompleteProductionOrder.id,
    reason: "Additional rework needed for quality defects",
  };

  it("reopens a technically complete order for additional execution", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // cost summary in PENDING_VARIANCE_REVIEW
    spies.select.mockReturnValueOnce({
      ...basePendingReviewCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });
    // update cost summary
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(reopened);

    const result = await run(db, validInput, ctx);

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

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

  it("returns error when no reopen reason is provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);

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

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

  it("reopens an order when the linked cost summary is PENDING_VARIANCE_REVIEW", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // cost summary in PENDING_VARIANCE_REVIEW
    spies.select.mockReturnValueOnce({
      ...basePendingReviewCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });
    // update cost summary
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(reopened);

    const result = await run(db, validInput, ctx);

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

  it("reopens an order when the linked cost summary is VARIANCE_REVIEWED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // cost summary in VARIANCE_REVIEWED
    spies.select.mockReturnValueOnce({
      ...baseReviewedCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });
    // update cost summary
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(reopened);

    const result = await run(db, validInput, ctx);

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

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

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // cost summary already SETTLED
    spies.select.mockReturnValueOnce({
      ...baseSettledCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });

    const result = await run(db, validInput, ctx);

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

  it("returns error when the order is already closed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseClosedProductionOrder);

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

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

  it("returns the linked cost summary to collecting on reopen", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    // order lookup
    spies.select.mockReturnValueOnce(baseTechCompleteProductionOrder);
    // cost summary in PENDING_VARIANCE_REVIEW
    spies.select.mockReturnValueOnce({
      ...basePendingReviewCostSummary,
      productionOrderId: baseTechCompleteProductionOrder.id,
    });
    // update cost summary to COLLECTING
    spies.update.mockReturnValueOnce(undefined);
    // update order status
    spies.update.mockReturnValue(reopened);

    const result = await run(db, validInput, ctx);

    expect(result.ok).toBe(true);
    // The first update call should be for cost summary (back to COLLECTING)
    // The second update call should be for order status (to IN_PROGRESS)
    expect(spies.update).toHaveBeenCalledTimes(2);
  });
});
