import { Comment, CommentNode } from "@/server/db/schema";

export function buildCommentTree(comments: Comment[]): Array<CommentNode> {
  // Create a map for quick access to nodes by their id
  const commentMap: Record<string, CommentNode> = {};

  // First pass: Create CommentNode objects for each comment
  comments.forEach((comment) => {
    commentMap[comment.id] = {
      ...comment,
      children: [],
    };
  });

  // Second pass: Build the tree by connecting children to parents
  const rootComments: CommentNode[] = [];

  comments.forEach((comment) => {
    const node = commentMap[comment.id];

    // If parentId is null or empty string, it's a root comment
    if (!comment.parentId) {
      rootComments.push(node!);
    } else {
      // Add as a child to its parent if parent exists
      const parent = commentMap[comment.parentId];
      if (parent) {
        parent.children.push(node!);
      } else {
        // Parent doesn't exist, treat as root comment
        rootComments.push(node!);
      }
    }
  });
  return rootComments;
}
