import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
import { requireAdmin } from '../../utils/auth.js'

export default defineEventHandler(async (event) => {
  try {
    await requireAdmin(event)

    const body = await validateBody(event, adminMemberCreateSchema)

    await connectDB()

    // Check if member already exists
    const existingMember = await Member.findOne({ email: body.email })
    if (existingMember) {
      throw createError({
        statusCode: 409,
        statusMessage: 'Member with this email already exists'
      })
    }

    const newMember = new Member({
      name: body.name,
      email: body.email,
      circle: body.circle,
      contributionAmount: body.contributionAmount,
      slackInvited: false
    })

    const savedMember = await newMember.save()

    return savedMember
  } catch (error) {
    if (error.statusCode) throw error

    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to create member'
    })
  }
})
