import { Player, Token } from "@prisma/client"
import jwt from "jsonwebtoken"
import { v4 as uuidv4 } from "uuid"
import prisma from "../../prisma"

const tokenLifetime = {
  REFRESH: 172800,
  ACCESS: 15,
}

export default async function createTokenDB<T>(
  payload: T & { player: Player; newTokenType: Token["type"] }
) {
  const { player, newTokenType } = payload

  // Sign a new access token
  const newToken = jwt.sign(
    { uuid: uuidv4(), user: player.id },
    process.env.ACCESS_TOKEN_SECRET as string,
    { expiresIn: tokenLifetime[newTokenType] }
  )

  // Save token to DB
  const newTokenDB = await prisma.token.create({
    data: {
      token: newToken,
      type: newTokenType,
      expires: new Date(Date.now() + tokenLifetime[newTokenType] + "000"),
      owner: {
        connect: {
          id: player.id,
        },
      },
    },
  })

  return {
    ...payload,
    newToken,
    newTokenDB,
  }
}
