import { awardPoints } from "../../utils/scoring";
import { createNotification } from "../../db/notifications";
import { getProfile } from "../../db/profile";
import {
  getPostLike,
  setPostLike,
  deletePostLike,
  countPostLikes,
  syncPostLikeCounts,
  getPostById,
} from "../../db/community";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const { postId, type } = (await readBody(event)) as {
    postId: string;
    type: "like" | "dislike";
  };

  if (!postId || !["like", "dislike"].includes(type)) {
    throw createError({
      statusCode: 400,
      message: "postId und type (like|dislike) erforderlich",
    });
  }

  const [existing, currentPost] = await Promise.all([
    getPostLike(user.id, postId),
    getPostById(postId),
  ]);

  let newUserLike: "like" | "dislike" | null = null;

  if (existing) {
    if (existing.type === type) {
      // Toggle OFF
      await deletePostLike(user.id, postId);
      newUserLike = null;
    } else {
      // Typ wechseln
      await setPostLike(user.id, postId, type);
      newUserLike = type;
    }
  } else {
    await setPostLike(user.id, postId, type);
    newUserLike = type;

    if (
      type === "like" &&
      currentPost?.userId &&
      currentPost.userId !== user.id
    ) {
      const pr = await getProfile(user.id).catch(() => null);
      const actorName = pr?.nickname ?? pr?.username ?? "Jemand";
      const actorAvatar = pr?.avatar ?? undefined;
      await Promise.all([
        awardPoints(currentPost.userId, "upvote_received").catch(() => {}),
        createNotification({
          recipientId: currentPost.userId,
          type: "new_like",
          actorName,
          actorAvatar,
          postId,
        }).catch(() => {}),
      ]);
    }
  }

  const { likes, dislikes } = await countPostLikes(postId);
  await syncPostLikeCounts(postId, likes, dislikes);

  return { likesCount: likes, dislikesCount: dislikes, userLike: newUserLike };
});
