/**
 * Manual test script for NetworkErrorDetector
 * Run with: npx tsx test-network-error-detector.ts
 */

import { NetworkErrorDetector } from './src/utils/NetworkErrorDetector';

async function testNetworkErrorDetector() {
  console.log('🧪 Testing NetworkErrorDetector\n');

  // Test 1: DNS Error
  console.log('Test 1: DNS Resolution Error (ENOTFOUND)');
  const dnsError = new Error('getaddrinfo ENOTFOUND api.example.com');
  (dnsError as any).code = 'ENOTFOUND';
  const dnsResult = await NetworkErrorDetector.classifyError(dnsError, 'Gemini API');
  console.log('  Is Network Error:', dnsResult.isNetworkError);
  console.log('  Error Type:', dnsResult.errorType);
  console.log('  User Message:', dnsResult.userMessage);
  console.log('  Formatted Log:', NetworkErrorDetector.formatErrorForLogging(dnsResult));
  console.log('');

  // Test 2: Timeout Error
  console.log('Test 2: Connection Timeout (ETIMEDOUT)');
  const timeoutError = new Error('connect ETIMEDOUT 142.250.185.10:443');
  (timeoutError as any).code = 'ETIMEDOUT';
  const timeoutResult = await NetworkErrorDetector.classifyError(timeoutError, 'Gemini API');
  console.log('  Is Network Error:', timeoutResult.isNetworkError);
  console.log('  Error Type:', timeoutResult.errorType);
  console.log('  User Message:', timeoutResult.userMessage);
  console.log('  Formatted Log:', NetworkErrorDetector.formatErrorForLogging(timeoutResult));
  console.log('');

  // Test 3: Fetch Failed (actual error from logs)
  console.log('Test 3: Fetch Failed Error (from your logs)');
  const fetchError = new Error('exception TypeError: fetch failed sending request');
  const fetchResult = await NetworkErrorDetector.classifyError(fetchError, 'Gemini API');
  console.log('  Is Network Error:', fetchResult.isNetworkError);
  console.log('  Error Type:', fetchResult.errorType);
  console.log('  User Message:', fetchResult.userMessage);
  console.log('  Formatted Log:', NetworkErrorDetector.formatErrorForLogging(fetchResult));
  console.log('');

  // Test 4: Non-network Error
  console.log('Test 4: Non-Network Error (Invalid API Key)');
  const apiError = new Error('Invalid API key provided');
  const apiResult = await NetworkErrorDetector.classifyError(apiError, 'Gemini API');
  console.log('  Is Network Error:', apiResult.isNetworkError);
  console.log('  User Message:', apiResult.userMessage);
  console.log('  Formatted Log:', NetworkErrorDetector.formatErrorForLogging(apiResult));
  console.log('');

  console.log('✅ Tests completed!');
  console.log('\n📝 Summary:');
  console.log('  - Network errors are detected and classified');
  console.log('  - User-friendly messages are provided');
  console.log('  - Technical details are preserved for logging');
  console.log('  - No overhead on successful requests (only runs on failures)');
}

testNetworkErrorDetector().catch(console.error);
