import Event from '../../models/event.js'
import { connectDB } from '../../utils/mongoose.js'
import mongoose from 'mongoose'

export default defineEventHandler(async (event) => {
  try {
    // Ensure database connection
    await connectDB()
    const identifier = getRouterParam(event, 'id')
    
    if (!identifier) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Event identifier is required'
      })
    }
    
    // Fetch event from database - try by slug first, then by ID
    let eventData
    
    // Check if identifier is a valid MongoDB ObjectId
    if (mongoose.Types.ObjectId.isValid(identifier)) {
      eventData = await Event.findById(identifier)
        .select('-registrations.email') // Hide emails for privacy
        .lean()
    }
    
    // If not found by ID or not a valid ObjectId, try by slug
    if (!eventData) {
      eventData = await Event.findOne({ slug: identifier })
        .select('-registrations.email') // Hide emails for privacy
        .lean()
    }
    
    if (!eventData) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Event not found'
      })
    }
    
    // Add computed fields
    const eventWithMeta = {
      ...eventData,
      id: eventData._id.toString(),
      registeredCount: eventData.registrations?.length || 0,
      isFull: eventData.maxAttendees ? 
        (eventData.registrations?.length || 0) >= eventData.maxAttendees : 
        false
    }
    
    return eventWithMeta
  } catch (error) {
    console.error('Error fetching event:', error)
    
    if (error.statusCode) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch event'
    })
  }
})