import { connectDB } from '../../utils/mongoose.js'
import Event from '../../models/event'

export default defineEventHandler(async (event) => {
  await connectDB()
  const member = await requireAuth(event)

  try {
    const now = new Date()

    const events = await Event.find({
      'registrations.memberId': member._id,
      isCancelled: { $ne: true },
      startDate: { $gte: now },
    })
      .select('title slug description startDate endDate location featureImage maxAttendees registeredCount')
      .sort({ startDate: 1 })
      .limit(10)

    return {
      events,
      count: events.length,
    }
  } catch (error) {
    console.error('Error fetching member events:', error)

    if (error.statusCode) {
      throw error
    }

    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch registered events',
    })
  }
})
