import { authOptions } from "../auth/[...nextauth]" import sendResponse from "@backend/sendResponse" import { rejectionErrors } from "@lib/backend/errors" import prisma from "@lib/prisma" import { Game } from "@prisma/client" import type { NextApiRequest, NextApiResponse } from "next" import { getServerSession } from "next-auth" type Data = { game: Game } export const getAnyRunningGame = (id: string) => prisma.game.findFirst({ where: { NOT: { state: "ended", }, users: { some: { userId: id, }, }, }, include: { gamePin: true, users: true, }, }) export default async function create( req: NextApiRequest, res: NextApiResponse ) { const session = await getServerSession(req, res, authOptions) if (!session?.user) { return sendResponse(req, res, rejectionErrors.unauthorized) } const { email, id } = session.user const gameDB = await getAnyRunningGame(id) if (!gameDB) return sendResponse(req, res, { message: `User <${email}> is in no game.`, statusCode: 204, type: ["debug", "infoCyan"], }) const { users, gamePin, ...game } = gameDB return sendResponse(req, res, { message: `User <${email}> asked for game: ${game.id}`, statusCode: 200, body: { game, }, type: ["debug", "infoCyan"], }) }