import Series from '../../../models/series.js'
import Event from '../../../models/event.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 id = getRouterParam(event, 'id')
    const body = await validateBody(event, adminSeriesItemUpdateSchema)
    
    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Series ID is required'
      })
    }
    
    // Find and update the series
    const series = await Series.findOne({ id: id })
    
    if (!series) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Series not found'
      })
    }
    
    // Update series fields
    if (body.title !== undefined) series.title = body.title
    if (body.description !== undefined) series.description = body.description
    if (body.type !== undefined) series.type = body.type
    if (body.totalEvents !== undefined) series.totalEvents = body.totalEvents
    if (body.isActive !== undefined) series.isActive = body.isActive
    
    await series.save()
    
    // Also update all related events with the new series information
    await Event.updateMany(
      { 'series.id': id, 'series.isSeriesEvent': true },
      {
        $set: {
          'series.title': series.title,
          'series.description': series.description,
          'series.type': series.type,
          'series.totalEvents': series.totalEvents
        }
      }
    )
    
    return {
      success: true,
      data: series
    }
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error updating series:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})