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 interface CloseBudgetInput {
  budgetId: string;
}

export async function run(db: Transaction, input: CloseBudgetInput, 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 !== "ACTIVE") {
    return err(new InvalidStateError(input.budgetId));
  }

  // Transition to CLOSED
  const updated = await db
    .updateTable("Budget")
    .set({
      status: "CLOSED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.budgetId)
    .returningAll()
    .executeTakeFirst();

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