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 body = await validateBody(event, adminSeriesUpdateSchema)
    const { id, title, description, type, totalEvents } = body

    // Update the series record
    const updatedSeries = await Series.findOneAndUpdate(
      { id },
      {
        title,
        description,
        type,
        totalEvents: totalEvents || null
      },
      { new: true }
    )

    if (!updatedSeries) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Series not found'
      })
    }

    // Update all events in this series with the new metadata
    await Event.updateMany(
      {
        'series.id': id,
        'series.isSeriesEvent': true
      },
      {
        $set: {
          'series.title': title,
          'series.description': description,
          'series.type': type,
          'series.totalEvents': totalEvents || null
        }
      }
    )

    return updatedSeries
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error updating series:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})
