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

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

function getProxyAgent() {
    const proxyUrl = `http://${PROXY_CONFIG.username}:${PROXY_CONFIG.password}@${PROXY_CONFIG.host}:${PROXY_CONFIG.port}`;
    return new HttpsProxyAgent(proxyUrl, { rejectUnauthorized: false });
}

async function solveRecaptcha() {
    const CAPSOLVER_API_KEY = 'CAP-F424C55AC7E0360F95AB48383D9A0FEBD7DD7BB358E39F21F4EA91CEFF923326';
    const postData = JSON.stringify({
        clientKey: CAPSOLVER_API_KEY,
        task: {
            type: 'ReCaptchaV3EnterpriseTaskProxyLess',
            websiteURL: 'https://www.b2b.usezapay.com.br/',
            websiteKey: '6LdyyJgpAAAAAI2M2_rLl0QRQ0osF9q3Hq9ZT0Bo',
            pageAction: '760_get_debts'
        }
    });

    return new Promise((resolve, reject) => {
        const req = https.request({
            hostname: 'api.capsolver.com',
            path: '/createTask',
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        }, (res) => {
            let data = '';
            res.on('data', d => data += d);
            res.on('end', async () => {
                const resJson = JSON.parse(data);
                const taskId = resJson.taskId;
                
                for(let i=0; i<30; i++) {
                    await new Promise(r => setTimeout(r, 3000));
                    const checkReq = https.request({
                        hostname: 'api.capsolver.com',
                        path: '/getTaskResult',
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' }
                    }, (cRes) => {
                        let cData = '';
                        cRes.on('data', d => cData += d);
                        cRes.on('end', () => {
                            const cJson = JSON.parse(cData);
                            if(cJson.status === 'ready') resolve(cJson.solution.gRecaptchaResponse);
                        });
                    });
                    checkReq.write(JSON.stringify({ clientKey: CAPSOLVER_API_KEY, taskId }));
                    checkReq.end();
                }
            });
        });
        req.write(postData);
        req.end();
    });
}

async function testPlaca(placa) {
    console.log(`Testando placa: ${placa}`);
    const token = await solveRecaptcha();
    console.log("Captcha resolvido.");

    const postData = JSON.stringify({
        store: 760,
        customer: { email: "teste@gmail.com" },
        service: { serviceType: 'debts', licensePlate: placa, email: "teste@gmail.com" }
    });

    const options = {
        hostname: 'api.b2b.usezapay.com.br',
        path: '/v1/zapi/ecommerce/debts/',
        method: 'POST',
        agent: getProxyAgent(),
        headers: {
            'Content-Type': 'application/json',
            'use-recaptcha-enterprise': 'true',
            'recaptcha-token': token,
            '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'
        }
    };

    const req = https.request(options, (res) => {
        let chunks = [];
        res.on('data', c => chunks.push(c));
        res.on('end', () => {
            let buffer = Buffer.concat(chunks);
            console.log("Status Zapay:", res.statusCode);
            console.log("Resposta:", buffer.toString());
        });
    });
    req.write(postData);
    req.end();
}

testPlaca("LUB1330");
