import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { stockAdjustmentLifecycle } from "../db/stockAdjustment.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { StockAdjustmentNotFoundError, InvalidStatusError } from "../lib/errors.generated";

export interface CancelStockAdjustmentInput {
  id: string;
}

/**
 * Function: cancelStockAdjustment
 *
 * Transitions a stock adjustment from DRAFT to CANCELLED status.
 * Only adjustments in DRAFT status can be cancelled.
 * No inventory or ledger changes occur.
 */
export async function run(
  db: Transaction,
  input: CancelStockAdjustmentInput,
  _ctx: CommandContext,
) {
  const result = await executeTransition({
    db,
    tableName: "StockAdjustment",
    statusField: "status",
    id: input.id,
    transition: "cancel",
    lifecycle: stockAdjustmentLifecycle,
    errors: {
      notFound: StockAdjustmentNotFoundError,
      invalidTransition: InvalidStatusError,
    },
  });
  if (!result.ok) return result;
  return ok({ stockAdjustment: result.value });
}
