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

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

/**
 * Function: getAccountGroup
 *
 * Retrieves a single account group by id or by code within a CoA.
 */
export async function run(db: ReadonlyDB<DB>, input: GetAccountGroupInput) {
  let query = db.selectFrom("AccountGroup").selectAll();

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

  const accountGroup = await query.executeTakeFirst();

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