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

const MEMORY_EMOJIS = ['🛡️', '💪', '🌟', '🧠', '🌊', '🎯', '🌱', '🔑'];
function shuffle<T>(arr: T[]): T[] {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const tmp = a[i]!; a[i] = a[j]!; a[j] = tmp;
  }
  return a;
}

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 old = await db.gameChallenge.findUnique({ where: { id } });

  if (!old) throw createError({ statusCode: 404, message: "Spiel nicht gefunden" });
  if (old.status !== "FINISHED" && old.status !== "CANCELLED") {
    throw createError({ statusCode: 409, message: "Spiel noch nicht beendet" });
  }

  const isChallenger = user.id === old.challengerId;
  const isOpponent = user.id === old.opponentId;
  if (!isChallenger && !isOpponent) {
    throw createError({ statusCode: 403, message: "Nicht autorisiert" });
  }

  const opponentId = isChallenger ? old.opponentId : old.challengerId;
  const opponentName = isChallenger ? old.opponentName : old.challengerName;
  if (!opponentId || !opponentName) {
    throw createError({ statusCode: 409, message: "Kein Gegner vorhanden" });
  }

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

  const isMemory = old.gameType === "memory";
  const memoryState = isMemory ? {
    cards: shuffle([...MEMORY_EMOJIS, ...MEMORY_EMOJIS]).map((emoji: string, id: number) => ({ id, emoji, matchedBy: null })),
    flipped: [],
    scores: { X: 0, O: 0 },
    mismatchRevealed: false,
  } : undefined;

  // Create rematch challenge with opponent pre-set and directly ACTIVE
  const rematch = await db.gameChallenge.create({
    data: {
      challengerId: user.id,
      challengerName: myName,
      opponentId,
      opponentName,
      status: "ACTIVE",
      gameType: old.gameType,
      ...(memoryState && { memoryState }),
    },
  });

  return { challengeId: rematch.id };
});
