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,
  ProductionOrderNotCancellableError,
  ExecutionAlreadyStartedError,
  InventoryHandoffExistsError,
} from "../lib/errors.generated";
import {
  baseDraftProductionOrder,
  baseReleasedProductionOrder,
  baseInProgressProductionOrder,
  basePendingWorkOrder,
  baseInProgressWorkOrder,
  baseCollectingCostSummary,
} from "../testing/fixtures";
import { run } from "./cancelProductionOrder";

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

  it("cancels a draft production order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const cancelled = { ...baseDraftProductionOrder, status: "CANCELLED" as const };

    mock.enqueueResults([baseDraftProductionOrder], [cancelled]);

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

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

  it("cancels a released order before execution starts", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const cancelled = { ...baseReleasedProductionOrder, status: "CANCELLED" as const };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [baseCollectingCostSummary],
      [],
      [cancelled],
    );

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

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

  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 status does not allow cancellation", 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(ProductionOrderNotCancellableError);
    }
  });

  it("returns error when execution evidence already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

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

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

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

  it("returns error when inventory handoff evidence already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const costSummaryWithActuals = {
      ...baseCollectingCostSummary,
      actualMaterialCost: 500,
    };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [costSummaryWithActuals],
    );

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

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

  it("cascades cancellation to pending work orders", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const cancelled = { ...baseReleasedProductionOrder, status: "CANCELLED" as const };

    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [basePendingWorkOrder],
      [baseCollectingCostSummary],
      [],
      [cancelled],
    );

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

    expect(result.ok).toBe(true);
    // update should be called at least twice: once for work orders, once for order
    expect(mock.updates.length).toBeGreaterThan(0);
  });
});
