export default defineEventHandler(async (event) => {
  const { code } = await readBody(event)
  const userId: string = event.context.params ? event.context.params.id : '@me'

  const user = await getUser(userId, event)

  if (!user.$isEmpty('minecraft')) {
    throw createError({ statusCode: 400, statusMessage: 'Minecraft already linked' })
  }

  let whitelistDoc
  try {
    whitelistDoc = await WhitelistModel.findOne({ code })

    if (!whitelistDoc) {
      throw createError({ statusCode: 500, statusMessage: 'Whitelist document was not found' })
    }
  } catch (e) {
    console.error('Failed to get whitelist document', e)

    throw createError('Failed to get whitelist document')
  }

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

  try {
    whitelistDoc.connected = true
    user.minecraft = { uuid: whitelistDoc.uuid, username: minecraftProfile.name }

    await whitelistDoc.save()
    await applyUsername(user)
  } catch (e) {
    console.error('Failed to update documents', e)

    throw createError('Failed to update documents')
  }

  return user.minecraft
})
