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,
  ProductionOrderNotClosableError,
  OpenWorkRemainsError,
  CostSummaryNotSettledError,
} from "../lib/errors.generated";
import {
  baseTechCompleteProductionOrder,
  baseCompletedProductionOrder,
  baseClosedProductionOrder,
  baseCompleteWorkOrder,
  baseCancelledWorkOrder,
  basePendingWorkOrder,
  baseSettledCostSummary,
  basePendingReviewCostSummary,
} from "../testing/fixtures";
import { run } from "./closeProductionOrder";

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

  it("closes a technically complete order with a settled cost summary", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const closed = { ...baseTechCompleteProductionOrder, status: "CLOSED" as const };

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

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

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

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

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

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

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

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

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

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