import prisma from "../../prisma"
import { rejectionErrors } from "../errors"
import sendError, { API } from "./sendError"
import type { Player } from "@prisma/client"

export default async function getPlayerByNameDB<T>(
  context: API<T>,
  username: string
) {
  // Find Player in DB if it still exists (just to make sure)
  const player = await Promise.any([
    prisma.player.findUniqueOrThrow({
      where: {
        username: username,
      },
    }),
    prisma.player.findUniqueOrThrow({
      where: {
        email: username,
      },
    }),
  ]).catch(() => null)
  if (player === null) throw sendError(context, rejectionErrors.playerNotFound)

  return player
}
