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

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

  const body = await validateBody(event, adminMemberUpdateSchema)
  const memberId = getRouterParam(event, 'id')

  await connectDB()

  // If email changed, check for duplicates
  const existing = await Member.findById(memberId)
  if (!existing) {
    throw createError({ statusCode: 404, statusMessage: 'Member not found' })
  }

  if (body.email !== existing.email) {
    const emailTaken = await Member.findOne({ email: body.email })
    if (emailTaken) {
      throw createError({ statusCode: 409, statusMessage: 'Email already in use by another member' })
    }
  }

  const updated = await Member.findByIdAndUpdate(memberId, {
    name: body.name,
    email: body.email,
    circle: body.circle,
    contributionTier: body.contributionTier,
    status: body.status,
  }, { new: true })

  return {
    _id: updated._id,
    name: updated.name,
    email: updated.email,
    circle: updated.circle,
    contributionTier: updated.contributionTier,
    status: updated.status,
    role: updated.role,
  }
})
