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

export interface GetTrialBalanceInput {
  id: string;
}

/**
 * Function: getTrialBalance
 *
 * Retrieves a single trial balance by id, along with its associated trial balance lines.
 */
export async function run(db: ReadonlyDB<DB>, input: GetTrialBalanceInput) {
  const result = await db
    .selectFrom("TrialBalance")
    .selectAll()
    .where("id", "=", input.id)
    .executeTakeFirst();

  const lines = result
    ? await db
        .selectFrom("TrialBalanceLine")
        .selectAll()
        .where("trialBalanceId", "=", input.id)
        .orderBy("accountCode", "asc")
        .execute()
    : [];

  return ok({ trialBalance: result ?? null, lines });
}
