import { ObjectId } from 'mongodb'

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

  const user = await getAuth(event)
  const config = useRuntimeConfig()

  const teamsColl = db.collection('teams')
  const usersColl = db.collection('users')

  const team = await teamsColl.findOneAndUpdate({ _id: new ObjectId(teamId) }, { $inc: { count: 1 } })

  if (!team.value) return createError({ statusCode: 500, statusMessage: 'Team niet gevonden'})

  await $fetch(config.discordHost + '/team/addteammember', {
    method: 'POST',
    body: { voiceChannelId: team.value.voiceChannelId, textChannelId: team.value.textChannelId, discordId: user.discord.id }
  })

  await usersColl.updateOne({ _id: new ObjectId(user._id) }, { $set: { 'team.id': teamId, 'team.admin': false }})

  return team
});
