export default defineEventHandler(async (event) => {
  console.log('[DEBUG] Testing Documenso connectivity...')
  
  try {
    // Test basic connectivity to Documenso
    const documensoBaseUrl = process.env.NUXT_DOCUMENSO_BASE_URL;
    const documensoApiKey = process.env.NUXT_DOCUMENSO_API_KEY;
    
    if (!documensoBaseUrl || !documensoApiKey) {
      return {
        success: false,
        message: 'Documenso configuration missing',
        error: {
          message: 'NUXT_DOCUMENSO_BASE_URL or NUXT_DOCUMENSO_API_KEY environment variables not set'
        }
      }
    }
    
    const testUrl = `${documensoBaseUrl}/api/v1/documents`
    
    const response = await $fetch(testUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${documensoApiKey}`,
        'Content-Type': 'application/json'
      },
      params: {
        perPage: 1 // Just get 1 document to test connectivity
      },
      retry: 0
    }) as any
    
    return {
      success: true,
      message: 'Documenso connectivity successful',
      endpoint: testUrl,
      response: {
        total: response.total || 0,
        documentsFound: response.documents ? response.documents.length : 0,
        statusCode: 200
      }
    }
  } catch (error: any) {
    console.error('[DEBUG] Documenso connectivity test failed:', error)
    
    return {
      success: false,
      message: 'Documenso connectivity failed',
      error: {
        message: error.message,
        status: error.status,
        statusCode: error.statusCode,
        cause: error.cause?.message
      }
    }
  }
})
