// apps/api/src/utils/http.js

const axios = require('axios');
const https = require('https');

class HttpClient {
    constructor() {
        this.defaultConfig = {
            timeout: 30000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-US,en;q=0.9',
                'Accept-Encoding': 'gzip, deflate',
                'Connection': 'keep-alive'
            },
            httpsAgent: new https.Agent({
                rejectUnauthorized: false,
                keepAlive: true
            })
        };
    }
    
    async get(url, config = {}) {
        try {
            const response = await axios.get(url, {
                ...this.defaultConfig,
                ...config
            });
            return response;
        } catch (error) {
            console.error(`HTTP GET error for ${url}:`, error.message);
            throw error;
        }
    }
    
    async post(url, data, config = {}) {
        try {
            const response = await axios.post(url, data, {
                ...this.defaultConfig,
                ...config
            });
            return response;
        } catch (error) {
            console.error(`HTTP POST error for ${url}:`, error.message);
            throw error;
        }
    }
    
    async getText(url, config = {}) {
        const response = await this.get(url, config);
        return response.data;
    }
    
    async getJSON(url, config = {}) {
        const response = await this.get(url, {
            ...config,
            headers: {
                ...this.defaultConfig.headers,
                'Accept': 'application/json',
                ...config.headers
            }
        });
        return response.data;
    }
    
    setUserAgent(userAgent) {
        this.defaultConfig.headers['User-Agent'] = userAgent;
    }
    
    setHeader(key, value) {
        this.defaultConfig.headers[key] = value;
    }
}

module.exports = new HttpClient();