import { ObjectId } from 'mongodb'

export default defineEventHandler(async (event) => {
  const user = await getAuth(event)

  const config = useRuntimeConfig()

  const teamsColl = db.collection('teams')
  const team = await teamsColl.findOneAndUpdate({ _id: new ObjectId(user.team.id) }, { $inc: { count: -1 }})

  const usersColl = db.collection('users')
  await usersColl.findOneAndUpdate({ _id: new ObjectId(user._id) }, { $unset: { team: "" } })

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

  if (team.value.count <= 1) {
    await teamsColl.deleteOne({ _id: new ObjectId(user.team.id )})

    await $fetch(config.discordHost + '/team/deletechannels', {
      method: 'POST',
      body: { voiceChannelId: team.voiceChannelId, textChannelId: team.textChannelId }
    })
  }
  return team
});