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

export type GetAccountInput = { id: string } | { companyId: string; code: string };

/**
 * Function: getAccount
 *
 * Retrieves a single GL account by id or by company-scoped code.
 */
export async function run(db: ReadonlyDB<DB>, input: GetAccountInput) {
  let query = db.selectFrom("Account").selectAll();

  if ("id" in input) {
    query = query.where("id", "=", input.id);
  } else {
    query = query.where("companyId", "=", input.companyId).where("code", "=", input.code);
  }

  const account = await query.executeTakeFirst();

  return ok({ account: account ?? null });
}
