import checkTokenIsValid from "@backend/components/checkTokenIsValid"
import createTokenDB from "@backend/components/createTokenDB"
import getPlayerByIdDB from "@backend/components/getPlayerByIdDB"
import getTokenDB from "@backend/components/getTokenDB"
import getTokenFromCookie from "@backend/components/getTokenFromCookie"
import sendError from "@backend/components/sendError"
import sendResponse from "@backend/components/sendResponse"
import { Player, Token } from "@prisma/client"
import type { NextApiRequest, NextApiResponse } from "next"

interface Data {
  token: string
}

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

  const { refreshToken, newPlayer } = await getTokenFromCookie(context)

  let player: Player, tokenDB: Token, cookie: string | undefined

  if (!newPlayer) {
    const token = await checkTokenIsValid(context, refreshToken)
    tokenDB = await getTokenDB(context, token)
    player = await getPlayerByIdDB(context, tokenDB)
  } else {
    player = newPlayer.player
    tokenDB = newPlayer.newTokenDB
    cookie = newPlayer.newToken.value
  }

  const { newToken, newTokenDB } = await createTokenDB(player, type)
  return sendResponse(context, {
    message: `Access-Token generated: ${newTokenDB.id} with Refreshtoken-Token: ${tokenDB.id}`,
    body: { token: newToken.value },
    type: ["debug", "infoCyan"],
    cookie,
  })
}
