import Series from '../../models/series.js'
import { connectDB } from '../../utils/mongoose.js'
import { requireAdmin } from '../../utils/auth.js'

export default defineEventHandler(async (event) => {
  try {
    const admin = await requireAdmin(event)
    await connectDB()

    const body = await validateBody(event, adminSeriesCreateSchema)

    // Create new series
    const newSeries = new Series({
      id: body.id,
      title: body.title,
      description: body.description,
      type: body.type || 'workshop_series',
      totalEvents: body.totalEvents || null,
      createdBy: admin.email
    })
    
    await newSeries.save()
    
    return {
      success: true,
      data: newSeries
    }
  } catch (error) {
    console.error('Error creating series:', error)
    
    if (error.code === 11000) {
      throw createError({
        statusCode: 400,
        statusMessage: 'A series with this ID already exists'
      })
    }
    
    if (error.statusCode) throw error
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})