const express = require('express');
const http = require('http');
const https = require('https');
const zlib = require('zlib');
const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios');

const PORT = 3003; // Porta diferente para evitar conflito com a API principal

// ---
// Configurações
// ---
const EXTERNAL_API_URL_MS = 'http://52.15.37.114/dk/api.php';

const PROXY_CONFIG = {
    enabled: true,
    host: 'gate.nodemaven.com',
    port: 8080,
    username: 'pkscabelim_gmail_com-country-br-ipv4-true',
    password: 'xcy2s9jsob'
};

const USER_AGENTS = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'];

// ---
// Funções Auxiliares
// ---
function getRandomUserAgent() { return USER_AGENTS[0]; }

function getProxyAgent() {
    if (!PROXY_CONFIG.enabled) return undefined;
    const proxyUrl = `http://${PROXY_CONFIG.username}:${PROXY_CONFIG.password}@${PROXY_CONFIG.host}:${PROXY_CONFIG.port}`;
    return new HttpsProxyAgent(proxyUrl);
}

async function makeRequest(options, postData, agent, retries = 3) {
    let lastError;
    const protocol = options.port === 80 ? http : https;

    for (let attempt = 1; attempt <= retries; attempt++) {
        try {
            return await new Promise((resolve, reject) => {
                const reqOptions = { ...options, agent, timeout: 60000 };
                const req = protocol.request(reqOptions, (res) => {
                    let chunks = [];
                    res.on('data', (chunk) => chunks.push(chunk));
                    res.on('end', () => {
                        let buffer = Buffer.concat(chunks);
                        let encoding = res.headers['content-encoding'];
                        try {
                            if (encoding === 'gzip') buffer = zlib.gunzipSync(buffer);
                            else if (encoding === 'deflate') buffer = zlib.inflateSync(buffer);
                            else if (encoding === 'br') buffer = zlib.brotliDecompressSync(buffer);
                            const data = buffer.toString('utf8');
                            try { resolve(JSON.parse(data)); } catch (e) { resolve(data); }
                        } catch (err) { reject(err); }
                    });
                });
                req.on('error', reject);
                if (postData) req.write(postData);
                req.end();
            });
        } catch (err) {
            lastError = err;
            if (attempt < retries) await sleep(2000 * attempt);
            else throw lastError;
        }
    }
}

async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

// ---
// Função Principal de Consulta MS
// ---
async function consultarMS(placa, renavam) {
    console.log(`[MS_SERVER] Consultando Placa: ${placa}, Renavam: ${renavam}`);
    try {
        const options = {
            hostname: '52.15.37.114',
            port: 80,
            path: `/dk/api.php?placa=${placa}&renavam=${renavam}`,
            method: 'GET',
            headers: { 'User-Agent': getRandomUserAgent() }
        };
        const response = await makeRequest(options, null, getProxyAgent());

        if (response && response.success) {
            return { success: true, placa, data: response };
        }
        return { success: false, error: response.error || 'Veículo não encontrado MS ou erro na API externa' };
    } catch (e) {
        console.error(`[MS_SERVER] Erro na consulta MS:`, e.message);
        return { success: false, error: e.message };
    }
}

// ---
// Servidor Express
// ---
const app = express();
app.use(express.json());

app.get('/consultar/ms/:placa/:renavam', async (req, res) => {
    const { placa, renavam } = req.params;

    if (!placa || !renavam) {
        return res.status(400).json({ success: false, error: 'Placa e Renavam são obrigatórios.' });
    }

    const resultado = await consultarMS(placa, renavam);
    res.json(resultado);
});

app.get('/', (req, res) => {
    res.json({
        status: 'online',
        message: 'Servidor MS de teste online',
        endpoint: '/consultar/ms/:placa/:renavam'
    });
});

app.listen(PORT, () => {
    console.log(`[MS_SERVER] Servidor de teste MS rodando na porta ${PORT}`);
});
