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

export default defineEventHandler(async (event) => {
  try {
    await connectDB()
    
    const query = getQuery(event)
    
    // Build filter for series events only
    const filter = {
      'series.isSeriesEvent': true,
      isVisible: query.includeHidden === 'true' ? { $exists: true } : true
    }
    
    // Filter by series type
    if (query.seriesType) {
      filter['series.type'] = query.seriesType
    }
    
    // Filter for upcoming series
    if (query.upcoming === 'true') {
      filter.startDate = { $gte: new Date() }
    }
    
    // Fetch all series events and group them by series.id
    const events = await Event.find(filter)
      .sort({ 'series.id': 1, 'series.position': 1, startDate: 1 })
      .select('-registrations')
      .lean()
    
    // Group events by series ID
    const seriesMap = new Map()
    
    events.forEach(event => {
      const seriesId = event.series?.id
      if (!seriesId) return
      
      if (!seriesMap.has(seriesId)) {
        seriesMap.set(seriesId, {
          id: seriesId,
          title: event.series.title,
          description: event.series.description,
          type: event.series.type,
          totalEvents: event.series.totalEvents,
          events: [],
          firstEventDate: event.startDate,
          lastEventDate: event.endDate
        })
      }
      
      const series = seriesMap.get(seriesId)
      series.events.push({
        ...event,
        id: event._id.toString()
      })
      
      // Update date range
      if (event.startDate < series.firstEventDate) {
        series.firstEventDate = event.startDate
      }
      if (event.endDate > series.lastEventDate) {
        series.lastEventDate = event.endDate
      }
    })
    
    // Convert to array and add computed fields
    const seriesArray = Array.from(seriesMap.values()).map(series => {
      const now = new Date()
      return {
        ...series,
        eventCount: series.events.length,
        startDate: series.firstEventDate,
        endDate: series.lastEventDate,
        isOngoing: series.firstEventDate <= now && series.lastEventDate >= now,
        isUpcoming: series.firstEventDate > now,
        isCompleted: series.lastEventDate < now,
        status: series.lastEventDate < now ? 'completed' : 
                series.firstEventDate <= now && series.lastEventDate >= now ? 'active' : 'upcoming'
      }
    })
    
    return seriesArray
  } catch (error) {
    console.error('Error fetching event series:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch event series'
    })
  }
})