import checkTokenIsValid from "@backend/components/checkTokenIsValid"
import getPlayerByIdDB from "@backend/components/getPlayerByIdDB"
import getTokenDB from "@backend/components/getTokenDB"
import getTokenFromCookie from "@backend/components/getTokenFromCookie"
import getUserFromBody from "@backend/components/getUserFromBody"
import sendError from "@backend/components/sendError"
import sendResponse from "@backend/components/sendResponse"
import updatePlayerDB from "@backend/components/updatePlayerDB"
import bcrypt from "bcrypt"
import type { NextApiRequest, NextApiResponse } from "next"

interface Data {
  registered: boolean
}

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

  const { refreshToken } = await getTokenFromCookie(context)
  const token = await checkTokenIsValid(context, refreshToken)
  const tokenDB = await getTokenDB(context, token)
  const { username, password } = await getUserFromBody(context)
  let player = await getPlayerByIdDB(context, tokenDB)
  player = await updatePlayerDB(context, player, {
    username,
    email: "arst",
    passwordHash: await bcrypt.hash(password, 10),
    anonymous: false,
  })

  return sendResponse(context, {
    message: "Player registered : " + player.id,
    statusCode: 201,
    body: { registered: true },
    type: ["debug", "infoCyan"],
  })
}
