// Update customer billing address
import { requireAuth } from '../../utils/auth.js'
import { updateHelcimCustomer } from '../../utils/helcim.js'

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

    const { billingAddress } = body

    const customerData = await updateHelcimCustomer(body.customerId, {
      billingAddress: {
        name: billingAddress.name,
        street1: billingAddress.street,
        city: billingAddress.city,
        province: billingAddress.province || billingAddress.state,
        country: billingAddress.country,
        postalCode: billingAddress.postalCode
      }
    })

    return {
      success: true,
      customer: customerData
    }
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error updating billing address:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})
