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

  const config = useRuntimeConfig()

  if (!code) return sendRedirect(event, '/', 302)

  try {
    const tokenResponseData = await $fetch('https://discord.com/api/oauth2/token', {
      method: 'POST',
      body: new URLSearchParams({
        client_id: config.discordId,
        client_secret: config.discordSecret,
        code: code,
        grant_type: 'authorization_code',
        redirect_uri: config.redirectURI,
        scope: 'identify',
      }).toString(),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

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

    const coll = db.collection('users')

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

    await coll.updateOne({ 'discord.id': userResult.id }, { $set: doc, $setOnInsert: { minecraft: { uuid: null, username: null }, teamInvites: [], role: {} } }, { upsert: true })
    
    const token = createToken(tokenResponseData.access_token, tokenResponseData.refresh_token, tokenResponseData.expires_in, userResult.id )

    setCookie(event, 'jwt', token, { httpOnly: true, maxAge: tokenResponseData.expires_in * 1000 })
  } catch (e) {
    console.log(e)

    throw createError({ statusCode: 500, statusMessage: 'Error tijdens het genereren van JWT token'})
  }

  return sendRedirect(event, '/', 302)
});
