// Network utilities
const https = require('https');

// Enhanced HTTPS request function with better error handling
const makeHttpsRequest = (url, options, postData = null) => {
    return new Promise((resolve, reject) => {
        const req = https.request(url, options, (res) => {
            let data = '';
            
            res.on('data', (chunk) => {
                data += chunk;
            });
            
            res.on('end', () => {
                try {
                    const parsedData = data ? JSON.parse(data) : {};
                    resolve({
                        status: res.statusCode,
                        headers: res.headers,
                        data: parsedData
                    });
                } catch (parseError) {
                    console.error('JSON Parse Error:', parseError);
                    console.error('Raw response data:', data);
                    resolve({
                        status: res.statusCode,
                        headers: res.headers,
                        data: { error: 'Invalid JSON response', rawData: data }
                    });
                }
            });
        });
        
        req.on('error', (error) => {
            console.error('HTTPS Request Error:', error);
            reject(error);
        });
        
        req.setTimeout(30000, () => {
            req.destroy();
            reject(new Error('Request timeout'));
        });
        
        if (postData) {
            req.write(postData);
        }
        
        req.end();
    });
};

// Retry network operations with exponential backoff
const retryNetworkOperation = async (operation, operationName, maxRetries = 3) => {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            console.error(`${operationName}: Attempt ${attempt}/${maxRetries}`);
            const result = await operation();
            
            // Consider 2xx status codes as success
            if (result.status >= 200 && result.status < 300) {
                return result;
            }
            
            // For 4xx errors, don't retry (client errors)
            if (result.status >= 400 && result.status < 500) {
                console.error(`${operationName}: Client error ${result.status}, not retrying`);
                return result;
            }
            
            // For 5xx errors, retry with backoff
            if (attempt < maxRetries) {
                const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
                console.error(`${operationName}: Server error ${result.status}, retrying in ${delay}ms`);
                await new Promise(resolve => setTimeout(resolve, delay));
                continue;
            }
            
            return result;
        } catch (error) {
            console.error(`${operationName}: Network error on attempt ${attempt}:`, error.message);
            
            if (attempt < maxRetries) {
                const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
                console.error(`${operationName}: Retrying in ${delay}ms`);
                await new Promise(resolve => setTimeout(resolve, delay));
                continue;
            }
            
            throw error;
        }
    }
};

module.exports = {
    makeHttpsRequest,
    retryNetworkOperation
};
