export default defineEventHandler(async (event) => {
  const { code } = await readBody(event)

  if (!code) throw createError({ statusCode: 400, statusMessage: 'Code is vereist'})
  
  const auth = await getAuth(event)

  const whitelistColl = db.collection('whitelist')
  const whitelistDoc = await whitelistColl.findOne({ code: code.toString() })

  if (!whitelistDoc) throw createError({ statusCode: 400, statusMessage: 'Code is niet gevonden, join eerste de Minecraft server' })
  if (whitelistDoc && whitelistDoc.verified) throw createError({ statusCode: 400, statusMessage: 'Already verified' })
  
  await whitelistColl.updateOne({ code: code.toString() }, { $set: { verified: true } })

  const minecraftProfile = await $fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${whitelistDoc.uuid}`)

  const usersColl = db.collection('users')
  await usersColl.updateOne({ 'discord.id': auth.discord.id }, { $set: { 'minecraft.uuid': whitelistDoc.uuid, 'minecraft.username': minecraftProfile.name } })


  return { uuid: whitelistDoc.uuid, verified: false, username: minecraftProfile.name }
});
