// Create a Helcim customer
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
import { createHelcimCustomer } from '../../utils/helcim.js'

export default defineEventHandler(async (event) => {
  try {
    await connectDB()
    const body = await validateBody(event, helcimCustomerSchema)

    // Check if member already exists
    const existingMember = await Member.findOne({ email: body.email })
    if (existingMember) {
      throw createError({
        statusCode: 409,
        statusMessage: 'A member with this email already exists'
      })
    }

    // Create customer in Helcim
    const customerData = await createHelcimCustomer({
      customerType: 'PERSON',
      contactName: body.name,
      email: body.email
    })

    // Create member in database
    const member = await Member.create({
      email: body.email,
      name: body.name,
      circle: body.circle,
      contributionAmount: body.contributionAmount,
      helcimCustomerId: customerData.id,
      status: 'pending_payment',
      agreement: { acceptedAt: new Date() }
    })

    setAuthCookie(event, member)

    return {
      success: true,
      customerId: customerData.id,
      customerCode: customerData.customerCode,
      member: {
        id: member._id,
        email: member.email,
        name: member.name,
        circle: member.circle,
        contributionAmount: member.contributionAmount,
        status: member.status
      }
    }
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error creating Helcim customer:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})
