import bcrypt from "bcrypt"
import prisma from "../../prisma"

async function createPlayerDB<T>(
  payload: T & { username: string; password: string }
) {
  const { username, password } = payload

  return await prisma.player
    .create({
      data: {
        username,
        passwordHash: await bcrypt.hash(password, 10),
        anonymous: false,
      },
    })
    .then((player) => {
      return { ...payload, player }
    })
    .catch((err: any) => {
      if (err.code === 11000) {
        return Promise.reject({
          message: `Duplicate key error while creating Player in DB!`,
          statusCode: 409,
          solved: true,
          type: "warn",
        })
      } else {
        console.log(err)
        return Promise.reject({
          message: `Unknown error while creating Player in DB.`,
          solved: false,
        })
      }
    })
}

export default createPlayerDB
