import jwt from 'jsonwebtoken'

const config = useRuntimeConfig()

export const createToken = (accessToken, refreshToken, maxAge, discordId) => {
  return jwt.sign({ accessToken, refreshToken, discordId }, config.jwtSecret, {
    expiresIn: maxAge,
  })
}

export const getAuth = async (event) => {
  const token = getCookie(event, 'jwt') || null

  if (!token) {
    throw createError({
      statusCode: 401,
      statusMessage: 'JWT token is niet geldig',
    })
  } 

  const config = useRuntimeConfig()
  
  let decodedToken;
  try {
    decodedToken = jwt.verify(token, config.jwtSecret)
  } catch (err) {
    console.log(err)

    throw createError({
      statusCode: 401,
      statusMessage: 'JWT token is niet geldig',
    })
  }
  
  try {
    const coll = db.collection("users")
    const user = await coll.findOne({ 'discord.id': decodedToken.discordId })

    user.accessToken = decodedToken.accessToken

    return user;
  } catch (err) {
    console.log(err)

    throw createError({
      statusCode: 500,
      statusMessage: 'Error tijdens ophalen van gegevens'
    })
  }
}
