import type { DB } from "../generated/kysely-tailordb";
import { ok, type ReadonlyDB } from "@tailor-platform/erp-kit/module";

export interface GetBudgetInput {
  id: string;
}

/**
 * Function: getBudget
 *
 * Retrieves a single budget by id, along with its line items.
 */
export async function run(db: ReadonlyDB<DB>, input: GetBudgetInput) {
  const budget = await db
    .selectFrom("Budget")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  if (!budget) {
    return ok({ budget: null, lineItems: [] });
  }

  const lineItems = await db
    .selectFrom("BudgetLineItem")
    .selectAll()
    .where("budgetId", "=", input.id)
    .execute();

  return ok({ budget, lineItems });
}
