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,
  ProductionOrderNotCompletableError,
  OpenWorkOrderRemainsError,
  FinalOutputRequiredError,
  FinalReceiptRequiredError,
} from "../lib/errors.generated";
import {
  baseInProgressProductionOrder,
  baseDraftProductionOrder,
  baseCompleteWorkOrder,
  baseCancelledWorkOrder,
  baseInProgressWorkOrder,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { run } from "./completeProductionOrder";

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

  it("completes an in-progress order after all required work orders finish", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const completed = { ...baseInProgressProductionOrder, status: "COMPLETED" as const };

    mock.enqueueResults(
      [baseInProgressProductionOrder],
      [baseCompleteWorkOrder, baseCancelledWorkOrder],
      [
        {
          ...baseCollectingCostSummary,
          productionOrderId: baseInProgressProductionOrder.id,
          actualMaterialCost: 500,
        },
      ],
      [completed],
    );

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

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

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

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

  it("returns error when required work orders remain open", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseInProgressProductionOrder],
      [baseInProgressWorkOrder, baseCompleteWorkOrder],
    );

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

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

  it("returns error when final output reporting is incomplete", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const completedWithZero = { ...baseCompleteWorkOrder, completedQuantity: 0 };

    mock.enqueueResults(
      [baseInProgressProductionOrder],
      [baseCancelledWorkOrder, completedWithZero],
    );

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

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

  it("returns error when required receipt handoff evidence is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    mock.enqueueResults(
      [baseInProgressProductionOrder],
      [baseCompleteWorkOrder],
      [
        {
          ...baseCollectingCostSummary,
          productionOrderId: baseInProgressProductionOrder.id,
          actualMaterialCost: 0,
        },
      ],
    );

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

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