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')
    
    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Series ID is required'
      })
    }
    
    // Find the series
    const series = await Series.findOne({ id: id })
    
    if (!series) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Series not found'
      })
    }
    
    // Remove series relationship from all related events
    await Event.updateMany(
      { 'series.id': id, 'series.isSeriesEvent': true },
      {
        $set: {
          'series.isSeriesEvent': false,
          'series.id': '',
          'series.title': '',
          'series.description': '',
          'series.type': 'workshop_series',
          'series.position': 1,
          'series.totalEvents': null
        }
      }
    )
    
    // Delete the series
    await Series.deleteOne({ id: id })
    
    return {
      success: true,
      message: 'Series deleted and events converted to standalone events'
    }
  } catch (error) {
    console.error('Error deleting series:', error)
    throw createError({
      statusCode: 500,
      statusMessage: error.message || 'Failed to delete series'
    })
  }
})