import { getCommentsByPost } from "../../../db/community";

/** GET /api/community/[postId]/comments */
export default defineEventHandler(async (event) => {
  const postId = getRouterParam(event, "postId");
  if (!postId) throw createError({ statusCode: 400, message: "postId fehlt" });

  let currentUserId: string | null = null;
  try {
    const u = await requireUser(event);
    currentUserId = u.id;
  } catch {}

  const { comments, userLikes } = await getCommentsByPost(
    postId,
    currentUserId,
  );

  return comments.map((c) => {
    const a = c.author;
    const username = a?.username ?? "Anonym";
    return {
      id: c.id,
      content: c.content,
      createdAt: c.createdAt,
      likesCount: c.likesCount ?? 0,
      userLike: userLikes.has(c.id),
      parentCommentId: c.parentReplyId ?? null,
      authorId: c.userId ?? null,
      authorNickname: a?.nickname ?? username,
      authorAvatar: a?.avatar ?? null,
      authorTier: "beginner",
    };
  });
});
