// Update member's circle
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
import { requireAuth } from '../../utils/auth.js'

export default defineEventHandler(async (event) => {
  try {
    const member = await requireAuth(event)
    await connectDB()
    const body = await validateBody(event, updateCircleSchema)

    if (member.circle === body.circle) {
      return { success: true, message: 'Already in this circle' }
    }

    await Member.findByIdAndUpdate(
      member._id,
      { $set: { circle: body.circle } },
      { runValidators: false }
    )

    return {
      success: true,
      message: `Circle updated to ${body.circle}`,
    }
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error updating circle:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred',
    })
  }
})
