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 DeactivateCostElementInput {
  costElementId: string;
}

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