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

type AccountGroupOrderByField = "code" | "name" | "sortOrder" | "createdAt";

export interface ListAccountGroupsInput extends PaginationInput<AccountGroupOrderByField> {
  chartOfAccountsId: string;
  parentAccountGroupId?: string | null;
}

/**
 * Function: listAccountGroups
 *
 * Lists account groups within a CoA, optionally filtered by parent group.
 * Results are sorted by sortOrder ascending by default.
 */
export async function run(db: ReadonlyDB<DB>, input: ListAccountGroupsInput) {
  const limit = input.limit ?? DEFAULT_PAGE_SIZE;
  const offset = input.offset ?? 0;
  const orderBy = input.orderBy ?? "sortOrder";
  const orderDirection = input.orderDirection ?? "asc";

  let query = db
    .selectFrom("AccountGroup")
    .selectAll()
    .where("chartOfAccountsId", "=", input.chartOfAccountsId);

  if (input.parentAccountGroupId !== undefined) {
    if (input.parentAccountGroupId === null) {
      query = query.where("parentAccountGroupId", "is", null);
    } else {
      query = query.where("parentAccountGroupId", "=", input.parentAccountGroupId);
    }
  }

  const groups = await query
    .orderBy(orderBy, orderDirection)
    .limit(limit + 1)
    .offset(offset)
    .execute();

  return ok(buildPaginatedResult(groups, limit));
}
