import type { Transaction } from "../generated/kysely-tailordb";
import { CostElementNotFoundError, InvalidStateError } from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface DeleteCostElementInput {
  costElementId: string;
}

/** Command: deleteCostElement
 * Permanently removes a cost element that is in DRAFT status.
 */
export async function run(db: Transaction, input: DeleteCostElementInput, ctx: CommandContext) {
  void ctx;

  const costElement = await db
    .selectFrom("CostElement")
    .selectAll()
    .where("id", "=", input.costElementId)
    .forUpdate()
    .executeTakeFirst();

  if (!costElement) {
    return err(new CostElementNotFoundError(input.costElementId));
  }

  if (costElement.status !== "DRAFT") {
    return err(new InvalidStateError(input.costElementId));
  }

  await db.deleteFrom("CostElement").where("id", "=", input.costElementId).executeTakeFirst();

  return ok({ costElement });
}
