const http = require('http');

function testEndpoint(path, options = {}) {
    return new Promise((resolve, reject) => {
        const req = http.request(`http://localhost:3000${path}`, options, (res) => {
            let data = '';
            res.on('data', chunk => data += chunk);
            res.on('end', () => {
                try {
                    const json = JSON.parse(data);
                    resolve({ status: res.statusCode, data: json });
                } catch {
                    resolve({ status: res.statusCode, data: data.slice(0, 200) });
                }
            });
        });
        req.on('error', reject);
        if (options.body) req.write(options.body);
        req.end();
    });
}

async function runTests() {
    console.log('\n=== Test 1: /api/countries (eval removed) ===');
    try {
        const result = await testEndpoint('/api/countries');
        console.log(`Status: ${result.status}`);
        if (Array.isArray(result.data)) {
            console.log(`Countries count: ${result.data.length}`);
            console.log(`First country: ${result.data[0]?.name || result.data[0]?.nameRu}`);
        } else {
            console.log('Error:', result.data);
        }
    } catch (e) {
        console.log('Request failed:', e.message);
    }

    console.log('\n=== Test 2: /api/rooms (using config) ===');
    try {
        const result = await testEndpoint('/api/rooms');
        console.log(`Status: ${result.status}`);
        if (Array.isArray(result.data)) {
            console.log(`Rooms count: ${result.data.length}`);
            result.data.forEach(r => console.log(` - ${r.type}: ${r.price_per_guest}₽`));
        }
    } catch (e) {
        console.log('Request failed:', e.message);
    }

    console.log('\n=== Test 3: Rate limiting on /api/promocodes/validate ===');
    for (let i = 1; i <= 22; i++) {
        try {
            const result = await testEndpoint('/api/promocodes/validate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code: 'TEST' })
            });
            if (i <= 3 || result.status === 429) {
                console.log(`Request ${i}: status ${result.status}${result.status === 429 ? ' (rate limited)' : ''}`);
            }
            if (result.status === 429 && i < 22) {
                console.log('Rate limit triggered at request', i);
                break;
            }
        } catch (e) {
            console.log(`Request ${i} error:`, e.message);
        }
    }

    console.log('\n=== All tests completed ===\n');
}

setTimeout(() => runTests().then(() => process.exit(0)), 2000);