import Event from '../../../models/event.js'
import Member from '../../../models/member.js'
import { connectDB } from '../../../utils/mongoose.js'
import { processHelcimPayment } from '../../../utils/helcim.js'
import mongoose from 'mongoose'

export default defineEventHandler(async (event) => {
  try {
    await connectDB()
    const identifier = getRouterParam(event, 'id')
    const body = await validateBody(event, eventPaymentSchema)

    if (!identifier) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Event identifier is required'
      })
    }
    
    // Fetch the event
    let eventData
    if (mongoose.Types.ObjectId.isValid(identifier)) {
      eventData = await Event.findById(identifier)
    }
    if (!eventData) {
      eventData = await Event.findOne({ slug: identifier })
    }
    
    if (!eventData) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Event not found'
      })
    }
    
    // Check if event requires payment
    if (eventData.pricing.isFree || !eventData.pricing.paymentRequired) {
      throw createError({
        statusCode: 400,
        statusMessage: 'This event does not require payment'
      })
    }
    
    // Check if user is already registered
    const existingRegistration = eventData.registrations.find(
      reg => reg.email.toLowerCase() === body.email.toLowerCase()
    )
    
    if (existingRegistration) {
      throw createError({
        statusCode: 400,
        statusMessage: 'You are already registered for this event'
      })
    }
    
    // Check if user is a member (members get free access)
    const member = await Member.findOne({ email: body.email.toLowerCase() })
    
    if (member) {
      // Members get free access - register directly without payment
      eventData.registrations.push({
        name: body.name,
        email: body.email.toLowerCase(),
        membershipLevel: `${member.circle}-${member.contributionTier}`,
        isMember: true,
        paymentStatus: 'not_required',
        amountPaid: 0
      })
      
      await eventData.save()
      
      return {
        success: true,
        message: 'Successfully registered as a member (no payment required)',
        registration: eventData.registrations[eventData.registrations.length - 1]
      }
    }
    
    // Process payment for non-members
    const paymentResult = await processHelcimPayment({
      amount: eventData.pricing.publicPrice,
      paymentToken: body.paymentToken,
      customerData: {
        name: body.name,
        email: body.email
      }
    })
    
    if (!paymentResult.success) {
      throw createError({
        statusCode: 400,
        statusMessage: paymentResult.message || 'Payment failed'
      })
    }
    
    // Add registration with successful payment
    eventData.registrations.push({
      name: body.name,
      email: body.email.toLowerCase(),
      membershipLevel: 'non-member',
      isMember: false,
      paymentStatus: 'completed',
      paymentId: paymentResult.transactionId,
      amountPaid: eventData.pricing.publicPrice
    })
    
    await eventData.save()
    
    return {
      success: true,
      message: 'Payment successful and registered for event',
      paymentId: paymentResult.transactionId,
      registration: eventData.registrations[eventData.registrations.length - 1]
    }
    
  } catch (error) {
    console.error('Error processing event payment:', error)
    
    if (error.statusCode) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to process payment and registration'
    })
  }
})