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

/** POST /api/games/challenge/[id]/live-toggle — toggle isLive flag */
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 },
    select: {
      challengerId: true,
      opponentId: true,
      isLive: true,
      status: true,
    },
  });

  if (!challenge)
    throw createError({ statusCode: 404, message: "Challenge nicht gefunden" });

  // Only participants can toggle
  if (challenge.challengerId !== user.id && challenge.opponentId !== user.id) {
    throw createError({ statusCode: 403, message: "Nicht berechtigt" });
  }

  const updated = await db.gameChallenge.update({
    where: { id },
    data: { isLive: !challenge.isLive },
    select: { isLive: true },
  });

  return { isLive: updated.isLive };
});
