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

  let whitelistDoc
  try {
    whitelistDoc = await WhitelistModel.findOneAndUpdate({ uuid }, {
      $set: {
        uuid
      },
      $setOnInsert: {
        code: generateCode(),
        connected: false
      }
    }, { returnDocument: 'after', upsert: true })

    return whitelistDoc
  } catch (e: any) {
    throw createError({ statusCode: 500, statusMessage: 'Failed to update/insert whitelist document' })
  }
})

const generateCode = () => {
  return Math.floor(100000 + Math.random() * 900000)
}
