/**
 * Test Pull Log ADMS dari 192.168.0.50:8080
 */
require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
const http = require('http');

const TARGET_IP = process.env.FINGERSPOT_DEVICE_IP || '192.168.0.50';
const PORT      = 8080;
const SN        = process.env.SERIAL_NUMBER || '616231023290570';

function getAdmsLog(path) {
    return new Promise((resolve) => {
        console.log(`\n[ADMS GET] Requesting http://${TARGET_IP}:${PORT}${path}...`);
        
        const req = http.request({
            hostname: TARGET_IP,
            port: PORT,
            path: path,
            method: 'GET',
            headers: {
                'User-Agent': 'iClock-Proxy/1.0',
                'Accept': '*/*',
                'Connection': 'keep-alive'
            },
            timeout: 15000
        }, (res) => {
            let body = '';
            res.on('data', chunk => body += chunk.toString());
            res.on('end', () => {
                console.log(`  🎉 RESPONS DITERIMA! Status: ${res.statusCode}`);
                console.log(`  Headers:`, res.headers);
                console.log(`  Body (first 500 chars):\n${body.substring(0, 500)}`);
                resolve(true);
            });
        });

        req.on('timeout', () => {
            req.destroy();
            console.log(`  ❌ Timeout setelah 15 detik`);
            resolve(false);
        });

        req.on('error', (err) => {
            console.log(`  ❌ Error: ${err.message}`);
            resolve(false);
        });

        req.end();
    });
}

async function run() {
    console.log('=======================================================');
    console.log(` TESTING ADMS GET LOGS FROM ${TARGET_IP}:${PORT}`);
    console.log('=======================================================');

    await getAdmsLog(`/iclock/cdata?SN=${SN}&table=ATTLOG`);
    await getAdmsLog(`/iclock/cdata?SN=${SN}&table=OPERLOG`);
    await getAdmsLog(`/iclock/getrequest?SN=${SN}`);

    console.log('\n=======================================================\n');
}

run();
