export type TreeNode<T> = T & { children: TreeNode<T>[] };

export function buildTree<T extends { id: string; parentNodeId: string | null }>(
  nodes: T[],
): TreeNode<T>[] {
  const nodeMap = new Map<string, TreeNode<T>>(
    nodes.map((node) => [node.id, { ...node, children: [] }]),
  );
  const roots: TreeNode<T>[] = [];

  for (const treeNode of nodeMap.values()) {
    if (!treeNode.parentNodeId) {
      roots.push(treeNode);
    } else {
      const parent = nodeMap.get(treeNode.parentNodeId);
      if (parent) {
        parent.children.push(treeNode);
      } else {
        roots.push(treeNode);
      }
    }
  }

  return roots;
}
