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,
  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";

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

  it("technically completes a completed order and opens variance review", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const techComplete = {
      ...baseCompletedProductionOrder,
      status: "TECHNICALLY_COMPLETE" as const,
    };

    mock.enqueueResults(
      [baseCompletedProductionOrder],
      [baseCompleteWorkOrder, baseCancelledWorkOrder],
      [{ ...baseCollectingCostSummary, productionOrderId: baseCompletedProductionOrder.id }],
      [],
      [techComplete],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseCompletedProductionOrder.id }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productionOrder.status).toBe("TECHNICALLY_COMPLETE");
    }
    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" }, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInProgressProductionOrder]);

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

    mock.enqueueResults([baseCompletedProductionOrder], [baseInProgressWorkOrder]);

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

    mock.enqueueResults(
      [baseCompletedProductionOrder],
      [baseCompleteWorkOrder, basePendingWorkOrder],
    );

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

    mock.enqueueResults(
      [baseCompletedProductionOrder],
      [baseCompleteWorkOrder],
      // cost summary already in PENDING_VARIANCE_REVIEW (not COLLECTING)
      [{ ...basePendingReviewCostSummary, productionOrderId: baseCompletedProductionOrder.id }],
    );

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

    mock.enqueueResults([baseCompletedProductionOrder], [basePausedWorkOrder]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: baseCompletedProductionOrder.id }, ctx),
    );

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