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

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

  const { gameName, score, nickname } = body;
  if (!gameName || typeof score !== "number" || score < 0) {
    throw createError({
      statusCode: 400,
      message: "gameName und score erforderlich",
    });
  }

  const db = usePrisma();
  const name = String(
    nickname ||
      user.user_metadata?.nickname ||
      user.email?.split("@")[0] ||
      "Anonym",
  ).slice(0, 30);

  // Nur updaten wenn neuer Score besser ist
  const existing = await db.gameHighScore.findUnique({
    where: { userId_gameName: { userId: user.id, gameName } },
  });

  if (!existing || score > existing.score) {
    await db.gameHighScore.upsert({
      where: { userId_gameName: { userId: user.id, gameName } },
      create: { userId: user.id, nickname: name, gameName, score },
      update: { score, nickname: name },
    });
  }

  return { ok: true, isNewBest: !existing || score > existing.score };
});
