import checkPasswordIsValid from "@backend/components/checkPasswordIsValid"
import getPlayerByNameDB from "@backend/components/getPlayerByNameDB"
import getUserFromBody from "@backend/components/getUserFromBody"
import sendError from "@backend/components/sendError"
import sendResponse from "@backend/components/sendResponse"
import prisma from "@lib/prisma"
import { NextApiRequest, NextApiResponse } from "next"

interface Data {
  loggedIn: boolean
}

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

  const { username, password } = await getUserFromBody(context)
  const player = await getPlayerByNameDB(context, username)
  await checkPasswordIsValid(context, player, password)
  prisma.player.update({
    where: {
      id: player.id,
    },
    data: {
      deleted: true,
      username: null,
      email: null,
      passwordHash: null,
    },
  })

  return sendResponse(context, {
    message: "User successfully deleted: " + player.id,
    type: ["debug", "infoCyan"],
  })
}
