const axios = require('/var/www/api_placa/node_modules/axios');
const CryptoJS = require('/var/www/api_placa/node_modules/crypto-js');
const { HttpsProxyAgent } = require('/var/www/api_placa/node_modules/https-proxy-agent');

// --- DADOS DO PAYLOAD FORNECIDO ---
const payload = {
    "response": "gBk6ixE05ShEvYtoX4XDpeZDECW60fl420NdY3Pif0B31aNsDqKfhPTstBlnDriryH1D8mVSJu9h4Q/IdZT+kUs6YmKpyqPVEKvMved7vRquQvkPwql3IDlSuMNuPl+2K4bv5ONU8wNgUPK+CKBLFmz8NiWP4lg1YSFpuTr8PzibVMtv1pnbo5eIN+fdadquzGxXgHCMTTeGvTY5wK1D+rsbCiWFHGH134igVCCZZXL41W4uRwq2WoicdLm2PqyADQKyybIcP0DB0yf9K8Sx1rfGMSTRvgTsWg8fWlG1KOM6abrGVelHNOwKhEAIdNQRpAFRWWfJVK6931r253dsRhAgMH2qw1XqUH20x6dSNpqa1QDxZ3HcrIL1/ZjrfIYgeGVnSNmk2NrL+Bh9fCaw+rguA3X1wEXYzv2idMXM786kcBijpPWL+H/ppfF5qIv5rqceKMCuI2SpgmX4uezhN5T9hwOoBlg656VRPGEN7XuhqV78khMZCGld0FeiLGgRNTNXNxumG2Fw1Li62y6x3Gh6FninsyqytFAh0BYbh57KDqfPAtr7n9ZPqXhTuTrILus0ScIKSMp2AW/LCCd2vXSJb0WXTPoRlcM/GmKL4hNgrv/GeRsXF8uYbV6+SdEN562wA9XxQH+Z4Oy+9aw7HB9bq4p8x4gHgMIbTOVP4zczTYOSw0JzjUMX35rPPW4u1NBSDRcFcCHdfiZTCx4xqTmNrRV497tm+CReWuJb68m3lkRQuPYxwKN4MOS5V5IB8/0UnSDgV9OeUl+vmBFTqJCnF30lP+yV33KwWxmOX/DnmanHUFvxMeQF3cA6DU2lm2OWpgYIZCtEPpuIH+tpu78607f1iPHluUq0oEmhlgtXDgNsf6s3UCQqpVDkk1PAjM47c24qy1/hxuNCBoLD70TI41npA7k/vLEN5uQwAYwpZ08m63GxlG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l7EPYvqbAYQ7SzrWpeamKHM8J50Qfv3LvW5gU9BkFnUwnbVtfIpd9bUDgllwy5k7qX9edGfha8honLtn9eNwjV5AFIBI8J6VDL5I26BqivpqxKTVEWZQDl4ej1nVGL5L1IK9wg+LgHB7YXVxTWMrkfo3m86cgJE4aoBuuD21Q+ToePCh9ccm3yBQyRHG4FEPa6282wvwAJezsagEzp81mD0AvoI=",
    "numberKey": "8xPt5KsvDGTEMLhdeZCtCA6s60fT4rW7H2QkqF9NotLMTBx5nw12VnI=",
    "dateIsoStringKey": "/JC0HBOAGIqIrdFkYPk6Z82gGnjlD9us+oeTrbo5yP/FWpjlsZ70Znsj8BFOLZyvyaZeIg=="
};

// --- FUNÇÃO DE DESCRIPTOGRAFIA (SIMULANDO ZIGNET) ---
function decryptZignet(data) {
    try {
        console.log("[Lab] Tentando descriptografar...");
        
        // A Zignet utiliza as chaves Base64 para gerar o segredo AES
        const key = CryptoJS.enc.Base64.parse(data.numberKey);
        const iv = CryptoJS.enc.Base64.parse(data.dateIsoStringKey);

        const decrypted = CryptoJS.AES.decrypt(data.response, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });

        const result = decrypted.toString(CryptoJS.enc.Utf8);
        if (result) {
            return JSON.parse(result);
        }
        return null;
    } catch (e) {
        console.error("[Lab] Erro na descriptografia:", e.message);
        return null;
    }
}

// --- FUNÇÃO DE CONSULTA (SIMULANDO CURL) ---
async function testZignetAPI(placa) {
    const proxyUrl = 'http://pkscabelim_gmail_com-country-br-ipv4-true:xcy2s9jsob@gate.nodemaven.com:8080';
    const agent = new HttpsProxyAgent(proxyUrl);

    const terminal = "4068707027";
    const fingerprint = "t9vF262pEP0uG0oFnk5q";

    const url = `https://nfbti53lkd.execute-api.us-east-2.amazonaws.com/dev/site/vehicle/${placa}?plate=${placa}&email=rickcooder@gmail.com&phone=62996494518&uf=GO&fingerprintId=${fingerprint}`;

    console.log(`[Lab] Consultando API AWS para placa: ${placa} via Proxy...`);
    
    try {
        const response = await axios.get(url, {
            headers: {
                "terminal": terminal,
                "x-fingerprint-site-id": fingerprint,
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                "origin": "https://www.zignet.com.br",
                "referer": "https://www.zignet.com.br/"
            },
            httpsAgent: agent,
            timeout: 15000
        });

        console.log("[Lab] Resposta da API:", JSON.stringify(response.data, null, 2));
        return response.data;
    } catch (error) {
        console.error("[Lab] Erro na requisição:", error.message);
        if (error.response) console.log("[Lab] Status:", error.response.status);
        return null;
    }
}

// --- EXECUÇÃO DO LABORATÓRIO ---
async function run() {
    // 1. Teste de Descriptografia com o JSON que você mandou
    const decryptedData = decryptZignet(payload);
    if (decryptedData) {
        console.log("[Lab] SUCESSO! Dados descriptografados:", JSON.stringify(decryptedData, null, 2));
    } else {
        console.log("[Lab] Falha ao descriptografar o payload de exemplo.");
    }

    // 2. Teste de Consulta Real com Proxy
    const apiResult = await testZignetAPI("PQA4703");
    if (apiResult) {
        console.log("[Lab] Consulta de placa finalizada.");
    }
}

run();
