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 SubmitStockAdjustmentInput {
  id: string;
}

/**
 * Function: submitStockAdjustment
 *
 * Transitions a stock adjustment from DRAFT to SUBMITTED status.
 * No inventory changes occur at this stage.
 */
export async function run(
  db: Transaction,
  input: SubmitStockAdjustmentInput,
  _ctx: CommandContext,
) {
  const result = await executeTransition({
    db,
    tableName: "StockAdjustment",
    statusField: "status",
    id: input.id,
    transition: "submit",
    lifecycle: stockAdjustmentLifecycle,
    errors: {
      notFound: StockAdjustmentNotFoundError,
      invalidTransition: InvalidStatusError,
    },
  });
  if (!result.ok) return result;
  return ok({ stockAdjustment: result.value });
}
