import * as jwt from 'jsonwebtoken'

interface IDecodedToken {
  discordId: string,
  userId: string,
  accessToken: string,
  refreshToken: string
}

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

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

  try {
    return jwt.verify(token, config.jwtSecret) as IDecodedToken
  } catch (e) {
    console.error('Failed to verify JWT token', e)

    throw createError({
      statusCode: 401,
      statusMessage: 'JWT token is invalid'
    })
  }
}

export const getUser = async (userId: string, event: any) => {
  if (userId === '@me') {
    const auth = getAuth(event)
    userId = auth.userId
  }

  try {
    const user = await UserModel.findById(userId)

    if (!user) {
      throw createError({ statusCode: 400, statusMessage: 'No user was found' })
    }

    return user
  } catch (e) {
    console.error('Failed to get user by id', e)

    throw createError({ statusCode: 500, statusMessage: 'Failed to get user' })
  }
}

export const applyUsername = async (user: IUser) => {
  if (user.usernameType === 'discord' || user.$isEmpty('minecraft') || !user.minecraft) {
    user.username = user.discord.username

    await user.save()
  } else {
    user.username = user.minecraft.username

    await user.save()
  }
}
