/**
 * TreeView lazy loading helper
 * @countermeasure/web-components/components/tree-view
 */

import { type TreeNode } from './types'

/**
 * Load children for a tree node using its lazyLoad function.
 * Caches the result on node.children after the first load.
 */
export async function loadChildren(node: TreeNode): Promise<TreeNode[]> {
  if (node.children !== undefined && node.children.length > 0) {
    return node.children
  }

  if (node.lazyLoad === undefined) {
    return []
  }

  const children = await node.lazyLoad()
  node.children = children
  return children
}
