export default defineEventHandler(async (event) => {
  const user = await getAuth(event)

  const userResult = await $fetch('https://discord.com/api/users/@me', {
    headers: {
      authorization: `Bearer ${user.accessToken}`
    }
  })

  const coll = db.collection('users')

  const doc = {
    discord: {
      id: userResult.id,
      username: userResult.username,
      avatarHash: userResult.avatar || null
    },
    username: user.useMinecraftUsername ? user.minecraft.username : userResult.username
  }

  const newUser = await coll.findOneAndUpdate({ 'discord.id': userResult.id }, { $set: doc }, { returnDocument: 'after' })

  applyUsername(newUser)

  return doc.discord
});
