// Get existing or create new Helcim customer (for upgrading members)
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 token = getCookie(event, 'auth-token')

    if (!token) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Not authenticated'
      })
    }

    // Decode JWT token
    let decoded
    try {
      decoded = jwt.verify(token, useRuntimeConfig().jwtSecret)
    } catch (err) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Invalid or expired token'
      })
    }

    // Get member
    const member = await Member.findById(decoded.memberId)
    if (!member) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Member not found'
      })
    }

    const helcimToken = config.helcimApiToken

    // First, search for existing customer
    try {
      const searchResponse = await fetch(
        `${HELCIM_API_BASE}/customers?search=${encodeURIComponent(member.email)}`,
        {
          headers: {
            'accept': 'application/json',
            'api-token': helcimToken
          }
        }
      )

      if (searchResponse.ok) {
        const searchData = await searchResponse.json()

        if (searchData.customers && searchData.customers.length > 0) {
          const existingCustomer = searchData.customers.find(c => c.email === member.email)

          if (existingCustomer) {

            // Update member record with customer ID if not already set
            if (!member.helcimCustomerId) {
              member.helcimCustomerId = existingCustomer.id
              await member.save()
            }

            return {
              success: true,
              customerId: existingCustomer.id,
              customerCode: existingCustomer.customerCode,
              existing: true
            }
          }
        }
      }
    } catch (searchError) {
      console.error('Error searching for customer:', searchError)
      // Continue to create new customer
    }

    // No existing customer found, create new one
    const createResponse = await fetch(`${HELCIM_API_BASE}/customers`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'content-type': 'application/json',
        'api-token': helcimToken
      },
      body: JSON.stringify({
        contactName: member.name,
        businessName: member.name,
        email: member.email
      })
    })

    if (!createResponse.ok) {
      const errorText = await createResponse.text()
      console.error('Failed to create Helcim customer:', createResponse.status, errorText)
      throw createError({
        statusCode: createResponse.status,
        statusMessage: 'Customer creation failed'
      })
    }

    const customerData = await createResponse.json()

    // Update member record with customer ID
    member.helcimCustomerId = customerData.id
    await member.save()

    return {
      success: true,
      customerId: customerData.id,
      customerCode: customerData.customerCode,
      existing: false
    }

  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error in get-or-create-customer:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})
