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

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

  const { role } = await validateBody(event, adminRoleUpdateSchema)
  const memberId = getRouterParam(event, 'id')

  // Prevent self-demotion
  if (admin._id.toString() === memberId && role !== 'admin') {
    throw createError({
      statusCode: 400,
      statusMessage: 'You cannot remove your own admin role.'
    })
  }

  const member = await Member.findByIdAndUpdate(
    memberId,
    { role },
    { new: true }
  )

  if (!member) {
    throw createError({
      statusCode: 404,
      statusMessage: 'Member not found.'
    })
  }

  return { success: true, member }
})
