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

export async function run(db: Transaction, input: DeleteBudgetInput, 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));
  }

  // Delete all associated line items
  await db.deleteFrom("BudgetLineItem").where("budgetId", "=", input.budgetId).execute();

  // Delete the budget
  await db.deleteFrom("Budget").where("id", "=", input.budgetId).execute();

  return ok({ budgetId: input.budgetId });
}
