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

export default defineEventHandler(async (event) => {
  const admin = 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,
    contributionAmount: body.contributionAmount,
    status: body.status,
  }, { new: true })

  // Log admin profile update
  const changedFields = []
  if (existing.name !== body.name) changedFields.push('name')
  if (existing.email !== body.email) changedFields.push('email')
  if (existing.circle !== body.circle) changedFields.push('circle')
  if (existing.contributionAmount !== body.contributionAmount) changedFields.push('contributionAmount')
  if (existing.status !== body.status) changedFields.push('status')

  if (changedFields.length) {
    logActivity(memberId, 'admin_profile_update', {
      fields: changedFields,
      changedBy: admin.name
    }, { performedBy: admin._id })
  }

  // Log status change separately for admin-only visibility
  if (existing.status !== body.status) {
    logActivity(memberId, 'status_changed', {
      from: existing.status,
      to: body.status
    }, { performedBy: admin._id })
  }

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