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

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const query = getQuery(event);
  const opponentId = query.opponentId as string | undefined;
  const limit = Math.min(Number(query.limit) || 10, 50);

  const db = usePrisma();

  const where = opponentId
    ? {
        OR: [
          { challengerId: user.id, opponentId },
          { challengerId: opponentId, opponentId: user.id },
        ],
        status: "FINISHED" as const,
      }
    : {
        OR: [
          { challengerId: user.id },
          { opponentId: user.id },
        ],
        status: "FINISHED" as const,
      };

  const games = await db.gameChallenge.findMany({
    where,
    orderBy: { updatedAt: "desc" },
    take: limit,
    select: {
      id: true,
      challengerId: true,
      challengerName: true,
      opponentId: true,
      opponentName: true,
      winner: true,
      createdAt: true,
      updatedAt: true,
    },
  });

  return games;
});
