import sendResponse from "@backend/components/sendResponse"
import getPlayer from "@lib/backend/components/getPlayer"
import prisma from "@lib/prisma"
import type { NextApiRequest, NextApiResponse } from "next"
import { z } from "zod"

export const createSchema = z.object({
  game: z.object({
    id: z.string(),
    createdAt: z.date(),
    updatedAt: z.date(),
    running: z.boolean(),
  }),
  pin: z.string().optional(),
  player: z.object({
    id: z.string(),
    username: z.string().optional(),
    isOwner: z.boolean().optional(),
  }),
  enemy: z
    .object({
      id: z.string(),
      username: z.string().optional(),
      isOwner: z.boolean().optional(),
    })
    .optional(),
})

type Data = z.infer<typeof createSchema>

export default async function create(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const context = { req, res }

  const { player } = await getPlayer(context)
  // Generate a random 4-digit code
  const pin = Math.floor(Math.random() * 10000)
    .toString()
    .padStart(4, "0")

  let created = false

  let game = await prisma.game.findFirst({
    where: {
      running: true,
      players: {
        some: {
          playerId: player.id,
        },
      },
    },
    include: {
      pin: true,
      players: true,
    },
  })
  if (!game) {
    created = true
    game = await prisma.game.create({
      data: {
        pin: {
          create: {
            pin,
          },
        },
        players: {
          create: {
            isOwner: true,
            playerId: player.id,
          },
        },
      },
      include: {
        pin: true,
        players: true,
      },
    })
  }

  return sendResponse(context, {
    message: `Player: ${player.id} created game: ${game.id}`,
    statusCode: created ? 201 : 200,
    body: {
      game,
      pin: game.pin?.pin,
      player: {
        id: player.id,
        username: player.username ?? undefined,
        isOwner: true,
      },
    },
    type: ["debug", "infoCyan"],
  })
}
