import { ObjectId } from 'mongodb'
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'
    })
  }
}

export const applyUsername = async (user) => {
  const teamsColl = db.collection('teams')
  const team = await teamsColl.findOne({ _id: new ObjectId(user.team.id) })

  const discordUsername = user.team ? user.username + ' [' + team.name + ']' : user.discord.username
  
  await $fetch(config.discordHost + '/user/changenickname', {
    method: 'POST',
    body: { nickname: discordUsername, discordId: user.discord.id }
  })
}

export const getUsernameWithTeam = async (user) => {
  const teamsColl = db.collection('teams')
  const team = user.team ? await teamsColl.findOne({ _id: new ObjectId(user.team.id) }): undefined;

  const username = user.team ? user.username + ` [<color:${team.color}>${team.name}</color>]` : user.username;
  const usernameWithoutStyle = user.team ? user.username + ` [${team.name}]` : user.username;

  return { username: username, usernameWithoutStyle: usernameWithoutStyle, team: team }
}
