// Get existing or create new Helcim customer (for upgrading members)
import Member from '../../models/member.js'
import { requireAuth } from '../../utils/auth.js'
import {
  getHelcimCustomer,
  findHelcimCustomerByEmail,
  createHelcimCustomer
} from '../../utils/helcim.js'

export default defineEventHandler(async (event) => {
  try {
    const member = await requireAuth(event)

    // 1. Short-circuit: member already has a Helcim customer ID on file.
    //    Verify it still resolves before falling through — otherwise we'd
    //    silently orphan the old customer and create a duplicate.
    if (member.helcimCustomerId) {
      try {
        const customer = await getHelcimCustomer(member.helcimCustomerId)
        if (customer?.id) {
          return {
            success: true,
            customerId: customer.id,
            customerCode: customer.customerCode,
            existing: true
          }
        }
      } catch (err) {
        // Only fall through on 404 (customer was deleted in Helcim).
        // Any other error must propagate — silently recreating was the
        // original duplicate-customer bug.
        if (err?.statusCode !== 404) throw err
      }
    }

    // 2. Fall back to search by email (case-insensitive match).
    let existingCustomer = null
    try {
      const searchData = await findHelcimCustomerByEmail(member.email)
      const memberEmail = member.email.toLowerCase()
      if (searchData.customers?.length) {
        existingCustomer = searchData.customers.find(
          c => c.email?.toLowerCase() === memberEmail
        ) || null
      }
    } catch (searchError) {
      console.error('Error searching for customer:', searchError)
      // Fall through to create
    }

    if (existingCustomer) {
      if (!member.helcimCustomerId) {
        await Member.findByIdAndUpdate(
          member._id,
          { $set: { helcimCustomerId: existingCustomer.id } },
          { runValidators: false }
        )
      }
      return {
        success: true,
        customerId: existingCustomer.id,
        customerCode: existingCustomer.customerCode,
        existing: true
      }
    }

    // 3. No match anywhere — create a fresh customer.
    const customerData = await createHelcimCustomer({
      contactName: member.name,
      businessName: member.name,
      email: member.email
    })

    await Member.findByIdAndUpdate(
      member._id,
      { $set: { helcimCustomerId: customerData.id } },
      { runValidators: false }
    )

    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'
    })
  }
})
