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

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const db = usePrisma();

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

  // Create game challenge
  const challenge = await db.gameChallenge.create({
    data: {
      challengerId: user.id,
      challengerName: name,
    },
  });

  // Auto-post in community so others can accept
  const post = await db.communityPost.create({
    data: {
      userId: user.id,
      category: "challenge",
      content: `${name} sucht einen Gegner für Tic-Tac-Toe! Wer nimmt die Challenge an?`,
      isAnonymous: false,
      isModerated: false,
      challengeId: challenge.id,
    },
  });

  // Link post back to challenge
  await db.gameChallenge.update({
    where: { id: challenge.id },
    data: { postId: post.id },
  });

  return { challengeId: challenge.id, postId: post.id };
});
