const axios = require('axios');

const BASE_URL = 'http://localhost:3001/api';

async function testPerformance() {
  console.log('Testing backend performance optimizations...\n');

  try {
    // Test 1: Health check
    console.log('1. Testing health check...');
    const start1 = Date.now();
    const healthResponse = await axios.get(`${BASE_URL}/health`);
    const healthTime = Date.now() - start1;
    console.log(`   Health check: ${healthTime}ms - Status: ${healthResponse.status}`);

    // Test 2: Compression
    console.log('\n2. Testing compression...');
    const start2 = Date.now();
    const productsResponse = await axios.get(`${BASE_URL}/products?limit=50`);
    const productsTime = Date.now() - start2;
    const contentLength = productsResponse.headers['content-length'];
    const contentEncoding = productsResponse.headers['content-encoding'];
    console.log(`   Products fetch: ${productsTime}ms - Size: ${contentLength} bytes - Compression: ${contentEncoding || 'none'}`);

    // Test 3: Lazy loading pagination
    console.log('\n3. Testing lazy loading pagination...');
    const start3 = Date.now();
    const ordersResponse = await axios.get(`${BASE_URL}/orders?page=1&limit=10`);
    const ordersTime = Date.now() - start3;
    const pagination = ordersResponse.data.pagination;
    console.log(`   Orders fetch: ${ordersTime}ms - Page: ${pagination.page}/${pagination.pages} - Has more: ${pagination.hasMore}`);

    // Test 4: Rate limiting
    console.log('\n4. Testing rate limiting...');
    const promises = [];
    for (let i = 0; i < 5; i++) {
      promises.push(axios.get(`${BASE_URL}/health`));
    }
    const start4 = Date.now();
    const rateLimitResults = await Promise.allSettled(promises);
    const rateLimitTime = Date.now() - start4;
    const successCount = rateLimitResults.filter(r => r.status === 'fulfilled').length;
    console.log(`   Rate limit test: ${rateLimitTime}ms - Success: ${successCount}/5`);

    console.log('\n✅ Performance test completed successfully!');
    console.log('\nOptimizations implemented:');
    console.log('• Database connection pooling');
    console.log('• Request compression');
    console.log('• Lazy loading with pagination');
    console.log('• Enhanced rate limiting');
    console.log('• Request timeout handling');
    console.log('• Better error handling');

  } catch (error) {
    console.error('❌ Performance test failed:', error.message);
    if (error.response) {
      console.error('Response status:', error.response.status);
      console.error('Response data:', error.response.data);
    }
  }
}

// Run the test if this file is executed directly
if (require.main === module) {
  testPerformance();
}

module.exports = { testPerformance }; 