import { NextApiRequest, NextApiResponse } from "next"
import createPlayerDB from "../../lib/backend/components/createPlayerDB"
import sendError from "../../lib/backend/components/sendError"
import sendResponse from "../../lib/backend/components/sendResponse"
import { Logging } from "../../lib/backend/logging"
import { Player } from "@prisma/client"

interface Data {
  registered: boolean
}

export default async function register(
  req: NextApiRequest,
  res: NextApiResponse<any>
) {
  const { username, password } = req.body
  return createPlayerDB({ req, res, username, password })
    .then(registerResponse<Data>)
    .then(sendResponse<Data>)
    .catch((err) => sendError(req, res, err))
}

async function registerResponse<T>(payload: {
  player: Player
  req: NextApiRequest
  res: NextApiResponse<T>
}) {
  const { player, req, res } = payload

  // Successfull response
  return {
    req,
    res,
    result: {
      message: "Player created : " + player.id,
      statusCode: 201,
      body: { registered: true },
      type: ["debug", "info.cyan"] as Logging[],
    },
  }
}
