import { awardPoints } from "../../utils/scoring";
import { createComment, getPostById } from "../../db/community";
import { getProfile } from "../../db/profile";
import { createNotification } from "../../db/notifications";

/** POST /api/community/comment */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const { postId, content, parentCommentId } = (await readBody(event)) as {
    postId: string;
    content: string;
    parentCommentId?: string;
  };

  if (!postId || !content?.trim()) {
    throw createError({
      statusCode: 400,
      message: "postId und content erforderlich",
    });
  }
  if (content.trim().length > 1000) {
    throw createError({
      statusCode: 400,
      message: "Kommentar zu lang (max. 1000 Zeichen)",
    });
  }

  const [data, pr, post] = await Promise.all([
    createComment(user.id, postId, content.trim(), parentCommentId ?? null),
    getProfile(user.id),
    getPostById(postId),
  ]);

  await awardPoints(user.id, "chat_message").catch(() => {});

  // Notification an Post-Autor (nicht an sich selbst)
  if (post?.userId && post.userId !== user.id) {
    const meta = user.user_metadata ?? {};
    const actorName =
      pr?.nickname ?? pr?.username ?? meta.full_name ?? "Jemand";
    const actorAvatar = pr?.avatar ?? undefined;
    createNotification({
      recipientId: post.userId,
      type: "new_comment",
      actorName,
      actorAvatar,
      postId,
      preview: content.trim().slice(0, 80),
    }).catch(() => {});
  }

  const meta = user.user_metadata ?? {};
  const username = pr?.username ?? "Anonym";

  return {
    id: data.id,
    content: data.content,
    createdAt: data.createdAt,
    likesCount: data.likesCount ?? 0,
    userLike: false,
    parentCommentId: data.parentReplyId ?? null,
    authorId: pr?.id ?? null,
    authorNickname: meta.nickname ?? meta.full_name ?? username,
    authorAvatar: meta.avatar ?? meta.avatar_url ?? meta.picture ?? null,
    authorTier: "beginner",
  };
});
