import { usePrisma } from "../../../../utils/prisma";
import { getProfile } from "../../../../db/profile";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const id = getRouterParam(event, "id");
  if (!id) throw createError({ statusCode: 400, message: "id fehlt" });

  const db = usePrisma();
  const challenge = await db.gameChallenge.findUnique({ where: { id } });

  if (!challenge) {
    throw createError({ statusCode: 404, message: "Challenge nicht gefunden" });
  }
  if (challenge.challengerId === user.id) {
    throw createError({ statusCode: 400, message: "Du kannst deine eigene Challenge nicht annehmen" });
  }
  if (challenge.status !== "OPEN") {
    throw createError({ statusCode: 409, message: "Challenge ist nicht mehr offen" });
  }

  const profile = await getProfile(user.id);
  const name = profile?.nickname || profile?.username || "Anonym";

  const updated = await db.gameChallenge.update({
    where: { id },
    data: {
      opponentId: user.id,
      opponentName: name,
      status: "ACTIVE",
    },
  });

  return updated;
});
