// Simple load test for FRE-634: Launch Week Technical Readiness
// Tests concurrent user handling

import http from 'http';

const CONFIG = {
  baseUrl: process.env.BASE_URL || 'http://localhost:3000',
  concurrentUsers: 1000,
  testDurationMs: 60000,
  endpoints: [
    '/',
    '/api/projects',
    '/api/characters',
    '/api/revisions'
  ]
};

async function makeRequest(endpoint) {
  return new Promise((resolve, reject) => {
    const start = Date.now();
    http.get(`${CONFIG.baseUrl}${endpoint}`, (res) => {
      resolve({
        endpoint,
        statusCode: res.statusCode,
        duration: Date.now() - start
      });
    }).on('error', (err) => {
      reject({ endpoint, error: err.message });
    });
  });
}

async function loadTest() {
  console.log(`Starting load test: ${CONFIG.concurrentUsers} users, ${CONFIG.testDurationMs}ms`);
  console.log(`Target: ${CONFIG.baseUrl}`);
  
  const results = [];
  const startTime = Date.now();
  
  while (Date.now() - startTime < CONFIG.testDurationMs) {
    const promises = [];
    for (let i = 0; i < CONFIG.concurrentUsers; i++) {
      const endpoint = CONFIG.endpoints[i % CONFIG.endpoints.length];
      promises.push(makeRequest(endpoint));
    }
    
    const batchResults = await Promise.all(promises);
    results.push(...batchResults);
  }
  
  const successRate = results.filter(r => r.statusCode === 200).length / results.length * 100;
  const avgDuration = results.reduce((a, b) => a + b.duration, 0) / results.length;
  
  console.log(`\nResults:`);
  console.log(`- Total requests: ${results.length}`);
  console.log(`- Success rate: ${successRate.toFixed(2)}%`);
  console.log(`- Average latency: ${avgDuration.toFixed(2)}ms`);
  console.log(`- Max concurrent: ${CONFIG.concurrentUsers}`);
  
  return {
    totalRequests: results.length,
    successRate,
    avgLatency: avgDuration,
    maxConcurrent: CONFIG.concurrentUsers
  };
}

loadTest().catch(console.error);
