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

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

/**
 * Function: getAccount
 *
 * Retrieves a single GL account by id or by code within a CoA.
 */
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("chartOfAccountsId", "=", input.chartOfAccountsId)
      .where("code", "=", input.code);
  }

  const account = await query.executeTakeFirst();

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