// Helcim API integration composable
export const useHelcim = () => {
  const config = useRuntimeConfig()
  const helcimToken = config.public.helcimToken

  // Base URL for Helcim API
  const HELCIM_API_BASE = 'https://api.helcim.com/v2'

  // Helper function to make API requests
  const makeHelcimRequest = async (endpoint, method = 'GET', body = null) => {
    try {
      const response = await $fetch(`${HELCIM_API_BASE}${endpoint}`, {
        method,
        headers: {
          'accept': 'application/json',
          'content-type': 'application/json',
          'api-token': helcimToken
        },
        body: body ? JSON.stringify(body) : undefined
      })
      return response
    } catch (error) {
      console.error('Helcim API error:', error)
      throw error
    }
  }

  // Create a customer
  const createCustomer = async (customerData) => {
    return await makeHelcimRequest('/customers', 'POST', {
      customerType: 'PERSON',
      contactName: customerData.name,
      email: customerData.email,
      billingAddress: customerData.billingAddress || {}
    })
  }

  // Create a subscription
  const createSubscription = async (customerId, planId, cardToken) => {
    return await makeHelcimRequest('/recurring/subscriptions', 'POST', {
      customerId,
      planId,
      cardToken,
      startDate: new Date().toISOString().split('T')[0] // Today's date
    })
  }

  // Get customer details
  const getCustomer = async (customerId) => {
    return await makeHelcimRequest(`/customers/${customerId}`)
  }

  // Get subscription details
  const getSubscription = async (subscriptionId) => {
    return await makeHelcimRequest(`/recurring/subscriptions/${subscriptionId}`)
  }

  // Update subscription
  const updateSubscription = async (subscriptionId, updates) => {
    return await makeHelcimRequest(`/recurring/subscriptions/${subscriptionId}`, 'PATCH', updates)
  }

  // Cancel subscription
  const cancelSubscription = async (subscriptionId) => {
    return await makeHelcimRequest(`/recurring/subscriptions/${subscriptionId}`, 'DELETE')
  }

  // Get payment plans
  const getPaymentPlans = async () => {
    return await makeHelcimRequest('/recurring/plans')
  }

  // Verify card token (for testing)
  const verifyCardToken = async (cardToken) => {
    return await makeHelcimRequest('/cards/verify', 'POST', {
      cardToken
    })
  }

  return {
    createCustomer,
    createSubscription,
    getCustomer,
    getSubscription,
    updateSubscription,
    cancelSubscription,
    getPaymentPlans,
    verifyCardToken
  }
}