/**
 * RPC Client with Retry Logic Example
 * 
 * This example demonstrates how to implement client-side retry logic
 * for handling 502 errors from Cloudflare tunnel.
 * 
 * Usage:
 *   node scripts/rpc-client-retry-example.js
 */

const https = require('https');

// Configuration
const RPC_URL = 'https://rpc.public-0138.defi-oracle.io';
const MAX_RETRIES = 3;
const BASE_DELAY = 1000; // 1 second base delay
const MAX_DELAY = 10000; // 10 seconds max delay

/**
 * Check if error is retryable
 */
function isRetryableError(error) {
  if (!error) return false;
  
  // Retry on 502, 503, 504, timeout, and network errors
  if (error.status === 502 || error.status === 503 || error.status === 504) {
    return true;
  }
  
  if (error.code === 'ETIMEDOUT' || error.code === 'ECONNRESET' || error.code === 'ENOTFOUND') {
    return true;
  }
  
  if (error.message && (
    error.message.includes('timeout') ||
    error.message.includes('502') ||
    error.message.includes('503') ||
    error.message.includes('504')
  )) {
    return true;
  }
  
  return false;
}

/**
 * Calculate exponential backoff delay
 */
function calculateDelay(attempt) {
  const delay = Math.min(BASE_DELAY * Math.pow(2, attempt), MAX_DELAY);
  // Add jitter to prevent thundering herd
  const jitter = Math.random() * 0.3 * delay; // Up to 30% jitter
  return delay + jitter;
}

/**
 * Sleep for specified milliseconds
 */
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * Make RPC request with retry logic
 */
async function rpcRequest(method, params = [], options = {}) {
  const maxRetries = options.maxRetries || MAX_RETRIES;
  const requestId = options.requestId || `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  
  const payload = JSON.stringify({
    jsonrpc: '2.0',
    method: method,
    params: params,
    id: 1
  });
  
  const requestOptions = {
    hostname: new URL(RPC_URL).hostname,
    port: 443,
    path: new URL(RPC_URL).pathname,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(payload),
      'X-Request-ID': requestId
    },
    timeout: options.timeout || 10000
  };
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const result = await makeRequest(requestOptions, payload);
      
      // Check for JSON-RPC errors
      if (result.error) {
        // Don't retry on JSON-RPC errors (method not found, invalid params, etc.)
        throw new Error(`RPC Error: ${result.error.message} (code: ${result.error.code})`);
      }
      
      if (attempt > 0) {
        console.log(`✅ Request ${requestId} succeeded on attempt ${attempt + 1}`);
      }
      
      return result;
      
    } catch (error) {
      const isLastAttempt = attempt === maxRetries - 1;
      const shouldRetry = isRetryableError(error);
      
      if (isLastAttempt || !shouldRetry) {
        console.error(`❌ Request ${requestId} failed after ${attempt + 1} attempts:`, error.message);
        throw error;
      }
      
      const delay = calculateDelay(attempt);
      console.warn(`⚠️ Request ${requestId} failed (attempt ${attempt + 1}/${maxRetries}), retrying in ${Math.round(delay)}ms...`, error.message);
      
      await sleep(delay);
    }
  }
}

/**
 * Make HTTP request
 */
function makeRequest(options, payload) {
  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        try {
          const parsed = JSON.parse(data);
          
          // Check HTTP status
          if (res.statusCode >= 500) {
            const error = new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`);
            error.status = res.statusCode;
            reject(error);
            return;
          }
          
          resolve(parsed);
        } catch (error) {
          reject(new Error(`Failed to parse response: ${error.message}`));
        }
      });
    });
    
    req.on('error', (error) => {
      reject(error);
    });
    
    req.on('timeout', () => {
      req.destroy();
      const error = new Error('Request timeout');
      error.code = 'ETIMEDOUT';
      reject(error);
    });
    
    req.write(payload);
    req.end();
  });
}

/**
 * Example usage
 */
async function main() {
  console.log('Testing RPC Client with Retry Logic\n');
  
  // Test 1: Simple request
  console.log('Test 1: eth_chainId');
  try {
    const result = await rpcRequest('eth_chainId', []);
    console.log('Result:', result.result);
  } catch (error) {
    console.error('Failed:', error.message);
  }
  
  console.log('\n');
  
  // Test 2: Multiple requests to test retry logic
  console.log('Test 2: Multiple requests (testing retry logic)');
  const requests = [];
  for (let i = 0; i < 5; i++) {
    requests.push(
      rpcRequest('eth_blockNumber', [])
        .then(result => ({ success: true, block: result.result }))
        .catch(error => ({ success: false, error: error.message }))
    );
  }
  
  const results = await Promise.all(requests);
  const successCount = results.filter(r => r.success).length;
  console.log(`Results: ${successCount}/${results.length} successful`);
  
  console.log('\n');
  
  // Test 3: With custom retry options
  console.log('Test 3: Custom retry options (max 5 retries)');
  try {
    const result = await rpcRequest('net_version', [], { maxRetries: 5 });
    console.log('Result:', result.result);
  } catch (error) {
    console.error('Failed:', error.message);
  }
}

// Run if executed directly
if (require.main === module) {
  main().catch(console.error);
}

module.exports = { rpcRequest, isRetryableError, calculateDelay };
