import { ok, executeTransition, type CommandContext } from "@tailor-platform/erp-kit/core";
import { costElementLifecycle } from "../db/costElement.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { CostElementNotFoundError, InvalidStateError } from "../lib/errors.generated";

export interface ActivateCostElementInput {
  costElementId: string;
}

/** Command: activateCostElement
 * Transitions a cost element from DRAFT status to ACTIVE status.
 */
export async function run(db: Transaction, input: ActivateCostElementInput, ctx: CommandContext) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "CostElement",
    statusField: "status",
    id: input.costElementId,
    transition: "activate",
    lifecycle: costElementLifecycle,
    errors: { notFound: CostElementNotFoundError, invalidTransition: InvalidStateError },
  });
  if (!result.ok) return result;
  return ok({ costElement: result.value });
}
