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)
    await connectDB()

    const members = await Member.find()
      .sort({ createdAt: -1 })
      .lean()

    return members
  } catch (error) {
    if (error.statusCode) throw error
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch members'
    })
  }
})
