import sendError from "@backend/components/sendError"
import sendResponse from "@backend/components/sendResponse"
import getPinFromBody from "@lib/backend/components/getPinFromBody"
import getPlayer from "@lib/backend/components/getPlayer"
import { rejectionErrors } from "@lib/backend/errors"
import prisma from "@lib/prisma"
import type { Game } from "@prisma/client"
import type { NextApiRequest, NextApiResponse } from "next"

interface Data {
  game: Game
}

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

  const pin = await getPinFromBody(context)
  const { player } = await getPlayer(context)
  try {
    const pinDB = await prisma.gamepin.update({
      where: {
        pin,
      },
      data: {
        game: {
          update: {
            players: {
              create: {
                isOwner: false,
                playerId: player.id,
              },
            },
          },
        },
      },
      include: {
        game: {
          include: {
            players: {
              include: {
                player: true,
              },
            },
          },
        },
      },
    })

    const enemy = pinDB.game.players.find(
      (enemy) => enemy.player.id !== player.id
    )
    return sendResponse(context, {
      message: `Player: ${player.id} joined game: ${pinDB.game.id}`,
      body: {
        game: pinDB.game,
        pin: pinDB.pin,
        player: {
          id: player.id,
          username: player.username ?? undefined,
          isOwner: true,
        },
        enemy: {
          id: enemy?.player.id,
          username: enemy?.player.username ?? undefined,
          isOwner: false,
        },
      },
      type: ["debug", "infoCyan"],
    })
  } catch (err: any) {
    console.log("HERE".red, err.code, err.meta, err.message)
    throw sendError(context, rejectionErrors.gameNotFound)
  }
}
