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

export interface CloseBudgetInput {
  budgetId: string;
}

export async function run(db: Transaction, input: CloseBudgetInput, ctx: CommandContext) {
  void ctx;
  const result = await executeTransition({
    db,
    tableName: "Budget",
    statusField: "status",
    id: input.budgetId,
    transition: "close",
    lifecycle: budgetLifecycle,
    errors: { notFound: BudgetNotFoundError, invalidTransition: InvalidStateError },
  });
  if (!result.ok) return result;
  return ok({ budget: result.value });
}
