export default defineEventHandler(async (event) => {
  const { teamName, teamColor } = await readBody(event);

  if (!teamName || !teamColor) return createError({ statusCode: 400, statusMessage: 'Team naam en kleur zijn vereist' })
  if (!isHexColor(teamColor)) return createError({ statusCode: 400, statusMessage: 'Team kleur is geen gelidige kleurencode' })
  if (!verifyUsername(teamName)) return createError({ statusCode: 400, statusMessage: 'Team naam moet alfanumeriek zijn en mag maximaal 20 tekens lang zijn' }) 

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

  if (user.team) return createError({ statusCode: 400, statusMessage: 'Gebruiker is al in een team' })

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

  if (await teamsColl.findOne({ name: { $regex: new RegExp(teamName, "i") } })) return createError({ statusCode: 400, statusMessage: 'Team naam bestaat al' })

  const discordResponse = await $fetch(config.discordHost + '/team/createchannels', {
    method: 'POST',
    body: { name: teamName, discordId: user.discord.id }
  })

  const response = await teamsColl.insertOne({ name: teamName, color: teamColor, count: 1, textChannelId: discordResponse.textChannel.id, voiceChannelId: discordResponse.voiceChannel.id })

  await usersColl.findOneAndUpdate({ 'discord.id': user.discord.id }, { $set: { 'team.id': response.insertedId.toString(), 'team.admin': true } })

  return response;
});
