import { ObjectId } from "mongodb";

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

  const currentUser = await getAuth(event)
  const userId = event.context.params.id;

  if (!reason) return createError({ statusCode: 400, statusMessage: 'Reason is vereist' })
  if (!currentUser.role.admin) return createError({ statusCode: 403, statusMessage: 'Geen toegang om gebruiker te bannen' })
  
  const usersColl = db.collection('users')
  const user = usersColl.findOneAndUpdate({ _id: new ObjectId(userId)}, { $set: { banned: { reason: reason, date: new Date() } } })

  if (!user.value) return createError({ statusCode: 500, statusMessage: 'Error tijdens het updaten van de gebruiker' })
  
  await $fetch(config.discordHost + '/user/ban', {
    method: 'POST',
    body: { reason: reason, discordId: user.discord.id }
  })

  await sendRconCommand(`ban ${user.value.minecraft.uuid} ${reason}`)

  return user
});
