// Get customer code for an existing 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 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'
      })
    }

    if (!member.helcimCustomerId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'No Helcim customer ID found'
      })
    }

    const helcimToken = config.helcimApiToken

    const response = await fetch(
      `${HELCIM_API_BASE}/customers/${member.helcimCustomerId}`,
      {
        headers: {
          'accept': 'application/json',
          'api-token': helcimToken
        }
      }
    )

    if (!response.ok) {
      const errorText = await response.text()
      throw createError({
        statusCode: response.status,
        statusMessage: 'Customer lookup failed'
      })
    }

    const customerData = await response.json()

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

  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error getting customer code:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred'
    })
  }
})
