import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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";

describe("reopenProductionOrder", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["manufacturing: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 mock = createKyselyMock<Namespace["main-db"]>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    mock.enqueueResults(
      [baseTechCompleteProductionOrder],
      [
        {
          ...basePendingReviewCostSummary,
          productionOrderId: baseTechCompleteProductionOrder.id,
        },
      ],
      [],
      [reopened],
    );

    const result = await mock.withTx((trx) => run(trx, validInput, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("IN_PROGRESS");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when the order does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseCompletedProductionOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseTechCompleteProductionOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    mock.enqueueResults(
      [baseTechCompleteProductionOrder],
      [
        {
          ...basePendingReviewCostSummary,
          productionOrderId: baseTechCompleteProductionOrder.id,
        },
      ],
      [],
      [reopened],
    );

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    mock.enqueueResults(
      [baseTechCompleteProductionOrder],
      [
        {
          ...baseReviewedCostSummary,
          productionOrderId: baseTechCompleteProductionOrder.id,
        },
      ],
      [],
      [reopened],
    );

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseTechCompleteProductionOrder],
      [
        {
          ...baseSettledCostSummary,
          productionOrderId: baseTechCompleteProductionOrder.id,
        },
      ],
    );

    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseClosedProductionOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const reopened = { ...baseTechCompleteProductionOrder, status: "IN_PROGRESS" as const };

    mock.enqueueResults(
      [baseTechCompleteProductionOrder],
      [
        {
          ...basePendingReviewCostSummary,
          productionOrderId: baseTechCompleteProductionOrder.id,
        },
      ],
      [],
      [reopened],
    );

    const result = await mock.withTx((trx) => run(trx, 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(mock.updates).toHaveLength(2);
  });
});
