# Troubleshooting API Issues - Pamsika WhatsApp Bot

## Overview

This guide helps resolve common API connection issues that occur when the bot tries to fetch product information from the PamsikaOnline API.

## Common Error: "socket hang up"

### Symptoms
- User selects a product (e.g., types "1")
- Bot shows: "Loading ticket options... Please wait."
- Error in logs: `Network error: socket hang up`
- User doesn't receive ticket type options

### Root Causes

1. **Network Timeout**: API server takes too long to respond
2. **Connection Reset**: Server closes connection unexpectedly  
3. **DNS Issues**: Cannot resolve the API domain
4. **Server Overload**: API server is temporarily unavailable
5. **Firewall/Proxy Issues**: Network blocks the connection

## Quick Fixes

### 1. Update API Client (Recommended)

The improved API client includes retry logic and better error handling:

```bash
# Backup original file
cp api/pamsikaClient.js api/pamsikaClient-backup.js

# The updated pamsikaClient.js already includes fixes:
# - 30-second timeout (increased from 10 seconds)
# - Automatic retry with exponential backoff
# - Better error categorization
# - Connection validation
```

### 2. Test API Connectivity

```bash
# Test API endpoint directly
curl -v "https://test.pamsikaonline.com/api/products/all"

# Test specific product prices
curl -v "https://test.pamsikaonline.com/api/products/product-prices/51"

# Test with timeout
curl --max-time 30 "https://test.pamsikaonline.com/api/products/product-prices/51"
```

### 3. Check Network Configuration

```bash
# Test DNS resolution
nslookup test.pamsikaonline.com

# Test connection
telnet test.pamsikaonline.com 443

# Check if running behind proxy
echo $HTTP_PROXY
echo $HTTPS_PROXY
```

## Advanced Troubleshooting

### Enable Detailed Logging

Add to your `.env` file:
```bash
NODE_ENV=development
LOG_LEVEL=debug
DEBUG=axios
```

### Monitor Network Traffic

```bash
# Install tcpdump (Linux/Mac)
sudo tcpdump -i any -n host test.pamsikaonline.com

# Or use Wireshark for detailed analysis
```

### Test with Different Timeout Values

Modify `api/pamsikaClient.js`:

```javascript
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 45000, // Increase to 45 seconds
  headers: {
    "Content-Type": "application/json",
    "User-Agent": "PamsikaBot/1.0",
  },
});
```

## Error Handling Improvements

### 1. Fallback Behavior

The improved API client now provides better user feedback:

```javascript
// If API fails, user sees:
"❌ Sorry, I'm having trouble loading ticket options for [Event Name] right now.

This could be due to:
• Network connectivity issues  
• Temporary server maintenance
• Event configuration being updated

Please try again in a few moments, or contact support at +265 995 684 047

Type *back* for events list or *menu* for main menu."
```

### 2. Retry Strategy

```javascript
// Automatic retry for these error types:
- ECONNABORTED (timeout)
- ECONNRESET (connection reset) 
- EPIPE (broken pipe)
- "socket hang up"
- HTTP 5xx errors

// Retry pattern:
- Attempt 1: Immediate
- Attempt 2: Wait 1 second  
- Attempt 3: Wait 2 seconds
- Attempt 4: Wait 4 seconds (final attempt)
```

## Prevention Strategies

### 1. Health Monitoring

Add API health checks to your monitoring:

```javascript
// Check API health every 5 minutes
setInterval(async () => {
  const { healthCheck } = require('./api/pamsikaClient');
  const isHealthy = await healthCheck();
  
  if (!isHealthy) {
    console.error('API health check failed');
    // Send alert to administrators
  }
}, 5 * 60 * 1000);
```

### 2. Circuit Breaker Pattern

```javascript
class ApiCircuitBreaker {
  constructor() {
    this.failureCount = 0;
    this.lastFailureTime = null;
    this.threshold = 5;
    this.timeout = 60000; // 1 minute
  }
  
  async call(apiFunction) {
    if (this.isOpen()) {
      throw new Error('Circuit breaker is open');
    }
    
    try {
      const result = await apiFunction();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }
  
  isOpen() {
    return this.failureCount >= this.threshold &&
           Date.now() - this.lastFailureTime < this.timeout;
  }
  
  onSuccess() {
    this.failureCount = 0;
    this.lastFailureTime = null;
  }
  
  onFailure() {
    this.failureCount++;
    this.lastFailureTime = Date.now();
  }
}
```

## Emergency Procedures

### 1. Temporary Disable Features

If API is consistently failing:

```javascript
// In config/settings.json
{
  "maintenanceMode": true,
  "maintenanceMessage": "🔧 Ticketing system is temporarily under maintenance. Please try again in 30 minutes. For urgent support, call +265 995 684 047"
}
```

### 2. Use Cached Data

```javascript
// Store last successful API response
const fs = require('fs');
const CACHE_FILE = './cache/products.json';

async function getCachedProducts() {
  try {
    if (fs.existsSync(CACHE_FILE)) {
      const cached = JSON.parse(fs.readFileSync(CACHE_FILE));
      const ageInMinutes = (Date.now() - cached.timestamp) / (1000 * 60);
      
      if (ageInMinutes < 30) { // Use cache if less than 30 minutes old
        return cached.products;
      }
    }
  } catch (error) {
    console.error('Error reading cache:', error);
  }
  return null;
}

async function cacheProducts(products) {
  try {
    const cacheData = {
      products,
      timestamp: Date.now()
    };
    fs.writeFileSync(CACHE_FILE, JSON.stringify(cacheData));
  } catch (error) {
    console.error('Error writing cache:', error);
  }
}
```

## Monitoring and Alerts

### 1. Set Up Alerts

```javascript
// Add to your monitoring system
const alerts = {
  apiFailureThreshold: 3, // Alert after 3 consecutive failures
  apiResponseTimeThreshold: 10000, // Alert if response > 10 seconds
  
  sendAlert: async (message) => {
    // Send SMS/Email/Slack notification
    console.error('ALERT:', message);
    // await sendSlackNotification(message);
  }
};
```

### 2. Log Analysis

```bash
# Monitor API errors in real-time
tail -f logs/combined.log | grep -i "api error\|network error\|socket hang up"

# Count errors by type
grep "Network error:" logs/combined.log | cut -d':' -f4 | sort | uniq -c

# Find slow requests
grep "timeout" logs/combined.log | tail -20
```

## Performance Optimization

### 1. Connection Pooling

```javascript
const https = require('https');

const agent = new https.Agent({
  keepAlive: true,
  keepAliveMsecs: 1000,
  maxSockets: 5,
  maxFreeSockets: 2,
  timeout: 30000
});

const apiClient = axios.create({
  httpsAgent: agent,
  // ... other config
});
```

### 2. Request Compression

```javascript
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    "Accept-Encoding": "gzip, deflate, br"
  }
});
```

## Testing API Reliability

### 1. Load Testing

```bash
# Install Apache Bench
sudo apt install apache2-utils

# Test API endpoint
ab -n 100 -c 10 "https://test.pamsikaonline.com/api/products/all"

# Test specific product endpoint
ab -n 50 -c 5 "https://test.pamsikaonline.com/api/products/product-prices/51"
```

### 2. Reliability Test Script

```javascript
// test-api-reliability.js
const { getAllProducts, getProductPrices } = require('./api/pamsikaClient');

async function testReliability() {
  const results = { success: 0, failure: 0, errors: [] };
  
  for (let i = 0; i < 20; i++) {
    try {
      console.log(`Test ${i + 1}/20`);
      const products = await getAllProducts();
      
      if (products.length > 0) {
        await getProductPrices(products[0].product_id);
      }
      
      results.success++;
    } catch (error) {
      results.failure++;
      results.errors.push(error.message);
      console.error(`Test ${i + 1} failed:`, error.message);
    }
    
    // Wait 2 seconds between tests
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
  
  console.log('Test Results:', results);
  console.log('Success Rate:', (results.success / 20 * 100).toFixed(1) + '%');
}

testReliability();
```

## Contact Information

**For technical support:**
- Phone: +265 995 684 047
- Email: inquiries@pamsikaonline.com

**For API issues:**
- Check API status at: https://test.pamsikaonline.com/api/health
- Report persistent issues to support team

**Emergency escalation:**
- If API is down for > 30 minutes
- If success rate < 80%
- If multiple users report issues

---

*Last Updated: December 2024*
*Version: 1.0*