import createPlayerDB from "./createPlayerDB"
import createTokenDB, { RawToken } from "./createTokenDB"
import type { API } from "./sendError"
import { Player, Token } from "@prisma/client"

interface Returning {
  refreshToken: RawToken
  newPlayer?: { player: Player; newToken: RawToken; newTokenDB: Token }
}

async function getTokenFromCookie<T>(context: API<T>): Promise<Returning> {
  const type = "REFRESH"
  const value = context.req.cookies.token

  // Checking for cookie presens, because it is necessary
  if (!value) {
    const player = await createPlayerDB()
    const { newToken, newTokenDB } = await createTokenDB(player, type)
    return {
      refreshToken: newToken,
      newPlayer: {
        player,
        newToken,
        newTokenDB,
      },
    }
  }
  return { refreshToken: { value, type } }
}

export default getTokenFromCookie
