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

export type UpdateBudgetInput = {
  budgetId: string;
  name?: string;
  description?: string | null;
  budgetHolderId?: string;
};
export async function run(db: Transaction, input: UpdateBudgetInput, ctx: CommandContext) {
  void ctx;

  // Fetch budget with lock
  const budget = await db
    .selectFrom("Budget")
    .where("id", "=", input.budgetId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!budget) {
    return err(new BudgetNotFoundError(input.budgetId));
  }

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

  // Apply updates
  const updated = await db
    .updateTable("Budget")
    .set({
      ...(input.name !== undefined && { name: input.name }),
      ...(input.description !== undefined && { description: input.description }),
      ...(input.budgetHolderId !== undefined && { budgetHolderId: input.budgetHolderId }),
      updatedAt: new Date(),
    })
    .where("id", "=", input.budgetId)
    .returningAll()
    .executeTakeFirst();

  return ok({ budget: updated! });
}
