const http = require('http');
require('dotenv').config();

const BASE_URL = process.env.TEST_URL || 'http://localhost:3000';

function makeRequest(options, postData = null) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        try {
          resolve({ status: res.statusCode, data: JSON.parse(data) });
        } catch (e) {
          resolve({ status: res.statusCode, data: data });
        }
      });
    });
    req.on('error', reject);
    if (postData) req.write(postData);
    req.end();
  });
}

async function testAPI() {
  console.log('\n🧪 Test API DecisionnelAssist - Transub\n');
  console.log('=' .repeat(40));

  let token = null;

  try {
    console.log('\n1️⃣  Test santé (Health Check)...');
    const health = await makeRequest({ hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/health', method: 'GET' });
    console.log(`   Status: ${health.status === 200 ? '✅' : '❌'} (${health.status})`);
    console.log(`   Uptime: ${health.data?.uptime || 'N/A'}s`);

    console.log('\n2️⃣  Test inscription...');
    const register = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/auth/register', method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    }, JSON.stringify({
      email: 'admin@transub.dz',
      password: 'Admin2024!',
      nom: 'Administrateur',
      role: 'admin'
    }));
    console.log(`   Status: ${register.status}`);

    console.log('\n3️⃣  Test connexion...');
    const login = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/auth/login', method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    }, JSON.stringify({
      email: 'admin@transub.dz',
      password: 'Admin2024!'
    }));
    console.log(`   Status: ${login.status === 200 ? '✅' : '❌'} (${login.status})`);
    token = login.data?.token || login.data?.data?.token;
    console.log(`   Token: ${token ? '✅ Reçu' : '❌ Non reçu'}`);

    if (!token) {
      console.log('\n⚠️  Impossible de tester sans token');
      return;
    }

    console.log('\n4️⃣  Test suggestion IA...');
    const suggestions = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/ia/suggestions', method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    console.log(`   Status: ${suggestions.status === 200 ? '✅' : '❌'} (${suggestions.status})`);
    console.log(`   Catégories: ${suggestions.data?.suggestions?.length || 0}`);

    console.log('\n5️⃣  Test query IA (recettes)...');
    const query1 = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/ia/query', method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
    }, JSON.stringify({ question: 'Combien de recettes cette semaine ?' }));
    console.log(`   Status: ${query1.status}`);
    console.log(`   Réponse: ${query1.data?.success ? '✅ OK' : '❌'}`);

    console.log('\n6️⃣  Test query IA (flotte)...');
    const query2 = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/ia/query', method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
    }, JSON.stringify({ question: 'État de la flotte' }));
    console.log(`   Status: ${query2.status}`);

    console.log('\n7️⃣  Test query IA (personnel)...');
    const query3 = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/ia/query', method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
    }, JSON.stringify({ question: 'Effectif total du personnel' }));
    console.log(`   Status: ${query3.status}`);

    console.log('\n8️⃣  Test statistiques...');
    const stats = await makeRequest({
      hostname: 'localhost', port: 3000, path: '/apidecisionnelAssist/ia/statistics', method: 'GET',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    console.log(`   Status: ${stats.status === 200 ? '✅' : '❌'} (${stats.status})`);
    console.log(`   Total queries: ${stats.data?.statistics?.total || 0}`);

    console.log('\n' + '='.repeat(40));
    console.log('✅ Tests terminés avec succès!\n');

  } catch (error) {
    console.error('\n❌ Erreur:', error.message);
  }
}

testAPI();