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, adminSeriesTicketsSchema)
    const { id, tickets } = body

    // Find the series
    const series = await Series.findOne({ id })

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

    // Update the series with new ticketing configuration
    const updatedSeries = await Series.findOneAndUpdate(
      { id },
      {
        $set: {
          tickets: {
            enabled: tickets.enabled || false,
            requiresSeriesTicket: tickets.requiresSeriesTicket || false,
            allowIndividualEventTickets: tickets.allowIndividualEventTickets !== false,
            currency: tickets.currency || 'CAD',
            member: {
              available: tickets.member?.available !== false,
              isFree: tickets.member?.isFree !== false,
              price: tickets.member?.price || 0,
              name: tickets.member?.name || 'Member Series Pass',
              description: tickets.member?.description || '',
              circleOverrides: tickets.member?.circleOverrides || {}
            },
            public: {
              available: tickets.public?.available || false,
              name: tickets.public?.name || 'Series Pass',
              description: tickets.public?.description || '',
              price: tickets.public?.price || 0,
              quantity: tickets.public?.quantity || null,
              sold: tickets.public?.sold || 0,
              reserved: tickets.public?.reserved || 0,
              earlyBirdPrice: tickets.public?.earlyBirdPrice || null,
              earlyBirdDeadline: tickets.public?.earlyBirdDeadline || null
            },
            capacity: {
              total: tickets.capacity?.total || null,
              reserved: tickets.capacity?.reserved || 0
            },
            waitlist: {
              enabled: tickets.waitlist?.enabled || false,
              maxSize: tickets.waitlist?.maxSize || null,
              entries: tickets.waitlist?.entries || []
            }
          },
          updatedAt: new Date()
        }
      },
      { new: true }
    )

    // If requiresSeriesTicket is enabled, update all events in the series
    if (tickets.enabled && tickets.requiresSeriesTicket) {
      await Event.updateMany(
        {
          'series.id': id,
          'series.isSeriesEvent': true
        },
        {
          $set: {
            'tickets.enabled': true,
            'tickets.requiresSeriesTicket': true,
            'tickets.seriesTicketReference': updatedSeries._id
          }
        }
      )
    } else if (tickets.enabled && !tickets.requiresSeriesTicket) {
      // If series tickets are optional, just mark the reference
      await Event.updateMany(
        {
          'series.id': id,
          'series.isSeriesEvent': true
        },
        {
          $set: {
            'tickets.seriesTicketReference': updatedSeries._id
          }
        }
      )
    } else {
      // If series tickets are disabled, remove the requirement from events
      await Event.updateMany(
        {
          'series.id': id,
          'series.isSeriesEvent': true
        },
        {
          $set: {
            'tickets.requiresSeriesTicket': false,
            'tickets.seriesTicketReference': null
          }
        }
      )
    }

    return {
      success: true,
      data: updatedSeries
    }
  } catch (error) {
    console.error('Error updating series ticketing:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'Failed to update series ticketing'
    })
  }
})
