import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";

export async function GET(_: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  
  // 최상위 댓글만 가져오기
  const topComments = await prisma.comment.findMany({
    where: { 
      postId: id,
      parentId: null, // 최상위 댓글만
    },
    orderBy: { createdAt: "asc" },
    include: {
      author: { select: { userId: true, nickname: true, profileImage: true } },
      replies: {
        include: {
          author: { select: { userId: true, nickname: true, profileImage: true } },
          replies: {
            include: {
              author: { select: { userId: true, nickname: true, profileImage: true } },
            },
            orderBy: { createdAt: "asc" },
          },
        },
        orderBy: { createdAt: "asc" },
      },
    },
  });
  
  // 재귀적으로 댓글 구조 변환
  const transformComment = (comment: any) => ({
    id: comment.id,
    parentId: comment.parentId,
    depth: comment.depth,
    content: comment.isSecret ? "비밀댓글입니다." : comment.content,
    isAnonymous: comment.isAnonymous,
    isSecret: comment.isSecret,
    author: comment.author ? {
      userId: comment.author.userId,
      nickname: comment.author.nickname,
      profileImage: comment.author.profileImage,
    } : null,
    anonId: comment.isAnonymous ? comment.id.slice(-6) : undefined,
    createdAt: comment.createdAt,
    updatedAt: comment.updatedAt,
    replies: comment.replies ? comment.replies.map(transformComment) : [],
  });
  
  const presented = topComments.map(transformComment);
  return NextResponse.json({ comments: presented });
}


