import { usePrisma } from "../../utils/prisma";

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const gameName = String(query.game || "").toLowerCase();

  const db = usePrisma();

  const where = gameName ? { gameName } : {};

  const [ratings, grouped] = await Promise.all([
    db.gameRating.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: 50,
      select: {
        id: true,
        userId: true,
        gameName: true,
        stars: true,
        feedback: true,
        score: true,
        createdAt: true,
      },
    }),
    db.gameRating.groupBy({
      by: ["gameName"],
      where,
      _avg: { stars: true },
      _count: { id: true },
    }),
  ]);

  // Profil-Daten für alle User laden
  const userIds = [...new Set(ratings.map((r) => r.userId))];
  const profiles =
    userIds.length > 0
      ? await db.profile.findMany({
          where: { id: { in: userIds } },
          select: { id: true, nickname: true, username: true, avatar: true },
        })
      : [];
  const profileMap = Object.fromEntries(profiles.map((p) => [p.id, p]));

  const ratingsWithUser = ratings.map((r) => {
    const profile = profileMap[r.userId];
    return {
      id: r.id,
      gameName: r.gameName,
      stars: r.stars,
      feedback: r.feedback,
      score: r.score,
      createdAt: r.createdAt,
      user: {
        nickname: profile?.nickname || profile?.username || "Anonym",
        avatar: profile?.avatar ?? null,
      },
    };
  });

  const stats = grouped.map((g) => ({
    gameName: g.gameName,
    avgStars: Math.round((g._avg.stars ?? 0) * 10) / 10,
    count: g._count.id,
  }));

  return { ratings: ratingsWithUser, stats };
});
