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

const HELCIM_API_BASE = 'https://api.helcim.com/v2'

export default defineEventHandler(async (event) => {
  try {
    await connectDB()
    const config = useRuntimeConfig(event)
    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'
      })
    }

    // Get token directly from environment if not in config
    const helcimToken = config.helcimApiToken
    
    if (!helcimToken) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Helcim API token not configured'
      })
    }

    
    // Test the connection first with native fetch
    try {
      const testResponse = await fetch('https://api.helcim.com/v2/connection-test', {
        method: 'GET',
        headers: {
          'accept': 'application/json',
          'api-token': helcimToken
        }
      })
      
      if (!testResponse.ok) {
        throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`)
      }
      
      await testResponse.json()
    } catch (testError) {
      console.error('Connection test failed:', testError)
      throw createError({
        statusCode: 401,
        statusMessage: 'Payment service unavailable'
      })
    }

    // Create customer in Helcim using native fetch
    const customerResponse = await fetch(`${HELCIM_API_BASE}/customers`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'content-type': 'application/json',
        'api-token': helcimToken
      },
      body: JSON.stringify({
        customerType: 'PERSON',
        contactName: body.name,
        email: body.email
      })
    })
    
    if (!customerResponse.ok) {
      const errorText = await customerResponse.text()
      console.error('Customer creation failed:', customerResponse.status, errorText)
      throw createError({
        statusCode: customerResponse.status,
        statusMessage: 'Customer creation failed'
      })
    }
    
    const customerData = await customerResponse.json()

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

    // Generate JWT token for the session
    const token = jwt.sign(
      { 
        memberId: member._id,
        email: body.email,
        helcimCustomerId: customerData.id 
      },
      config.jwtSecret,
      { expiresIn: '7d' }
    )

    // Set the session cookie server-side
    setCookie(event, 'auth-token', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7 days (matches verify.get.js and refresh.post.js)
      path: '/',
      domain: undefined // Let browser set domain automatically
    })
    return {
      success: true,
      customerId: customerData.id,
      customerCode: customerData.customerCode,
      token,
      member: {
        id: member._id,
        email: member.email,
        name: member.name,
        circle: member.circle,
        contributionTier: member.contributionTier,
        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'
    })
  }
})