/**
 * Script pour tester l'endpoint /api/admin/statistics
 */
import { pool } from '../db.js';

async function testStatisticsAPI() {
  try {
    console.log('🔄 Test de l\'endpoint /admin/statistics...\n');

    // D'abord, récupérer un admin pour avoir le token
    const adminResult = await pool.query(`
      SELECT id, email, first_name, last_name
      FROM users
      WHERE role = 'ADMIN'
      LIMIT 1
    `);

    if (adminResult.rows.length === 0) {
      console.log('⚠️  Aucun admin trouvé dans la base de données');
      console.log('   Créez un admin d\'abord avec:');
      console.log('   npm run db:seed');
      process.exit(1);
    }

    const admin = adminResult.rows[0];
    console.log(`✅ Admin trouvé: ${admin.email} (${admin.first_name} ${admin.last_name})`);
    console.log('   Note: Pour tester l\'API, vous devez vous connecter via l\'interface ou utiliser curl/Postman\n');

    // Simuler ce que l'endpoint retournerait en appelant directement les mêmes requêtes
    console.log('📊 Simulation des statistiques (requêtes SQL directes):\n');

    // Statistiques utilisateurs
    const usersStats = await pool.query(`
      SELECT
        COUNT(*) as total_users,
        COUNT(CASE WHEN role = 'CLIENT' THEN 1 END) as clients,
        COUNT(CASE WHEN role = 'EMPLOYEE' THEN 1 END) as employees,
        COUNT(CASE WHEN role = 'ADMIN' THEN 1 END) as admins,
        COUNT(CASE WHEN is_verified = TRUE THEN 1 END) as verified_users
      FROM users
    `);

    console.log('👥 Utilisateurs:');
    console.log(`   - Total: ${usersStats.rows[0].total_users}`);
    console.log(`   - Clients: ${usersStats.rows[0].clients}`);
    console.log(`   - Employés: ${usersStats.rows[0].employees}`);
    console.log(`   - Admins: ${usersStats.rows[0].admins}`);
    console.log(`   - Emails vérifiés: ${usersStats.rows[0].verified_users}\n`);

    // Statistiques tickets
    const ticketsStats = await pool.query(`
      SELECT
        COUNT(*) as total_tickets,
        COUNT(CASE WHEN user_id IS NOT NULL THEN 1 END) as distributed,
        COUNT(CASE WHEN played_at IS NOT NULL THEN 1 END) as used,
        COUNT(CASE WHEN status = 'PENDING' THEN 1 END) as pending,
        COUNT(CASE WHEN status = 'CLAIMED' THEN 1 END) as claimed,
        COUNT(CASE WHEN status = 'REJECTED' THEN 1 END) as rejected,
        COUNT(CASE WHEN validated_at IS NOT NULL THEN 1 END) as validated
      FROM tickets
    `);

    console.log('🎫 Tickets:');
    console.log(`   - Total: ${ticketsStats.rows[0].total_tickets}`);
    console.log(`   - Distribués: ${ticketsStats.rows[0].distributed}`);
    console.log(`   - Utilisés: ${ticketsStats.rows[0].used}`);
    console.log(`   - En attente: ${ticketsStats.rows[0].pending}`);
    console.log(`   - Validés: ${ticketsStats.rows[0].validated}`);
    console.log(`   - Réclamés: ${ticketsStats.rows[0].claimed}`);
    console.log(`   - Rejetés: ${ticketsStats.rows[0].rejected}\n`);

    // Répartition des lots
    const prizeDistribution = await pool.query(`
      SELECT
        p.id as prize_id,
        p.name as prize_name,
        p.type as prize_type,
        COUNT(t.id) as count,
        CASE
          WHEN (SELECT COUNT(*) FROM tickets) > 0
          THEN ROUND((COUNT(t.id)::DECIMAL / (SELECT COUNT(*) FROM tickets)) * 100, 2)
          ELSE 0
        END as percentage
      FROM prizes p
      LEFT JOIN tickets t ON p.id = t.prize_id
      GROUP BY p.id, p.name, p.type
      ORDER BY count DESC
    `);

    console.log('🎁 Répartition des lots:');
    prizeDistribution.rows.forEach(prize => {
      console.log(`   - ${prize.prize_name}: ${prize.count} (${prize.percentage}%)`);
    });
    console.log('');

    // Statistiques démographiques - Genre
    const genderStats = await pool.query(`
      SELECT
        COUNT(CASE WHEN gender = 'MALE' THEN 1 END) as male,
        COUNT(CASE WHEN gender = 'FEMALE' THEN 1 END) as female,
        COUNT(CASE WHEN gender = 'OTHER' THEN 1 END) as other,
        COUNT(CASE WHEN gender = 'NOT_SPECIFIED' OR gender IS NULL THEN 1 END) as not_specified
      FROM users
      WHERE role = 'CLIENT'
    `);

    console.log('👤 Démographie - Genre:');
    console.log(`   - Hommes: ${genderStats.rows[0].male}`);
    console.log(`   - Femmes: ${genderStats.rows[0].female}`);
    console.log(`   - Autre: ${genderStats.rows[0].other}`);
    console.log(`   - Non spécifié: ${genderStats.rows[0].not_specified}\n`);

    // Statistiques démographiques - Âge
    const ageStats = await pool.query(`
      SELECT
        age_range as range,
        COUNT(*) as count,
        ROUND((COUNT(*)::DECIMAL / (SELECT COUNT(*) FROM users WHERE role = 'CLIENT')) * 100, 2) as percentage
      FROM (
        SELECT
          CASE
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) BETWEEN 18 AND 25 THEN '18-25'
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) BETWEEN 26 AND 35 THEN '26-35'
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) BETWEEN 36 AND 45 THEN '36-45'
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) BETWEEN 46 AND 55 THEN '46-55'
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) BETWEEN 56 AND 65 THEN '56-65'
            WHEN EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth)) > 65 THEN '65+'
            ELSE 'Non spécifié'
          END as age_range
        FROM users
        WHERE role = 'CLIENT'
      ) subquery
      GROUP BY age_range
      ORDER BY
        CASE age_range
          WHEN '18-25' THEN 1
          WHEN '26-35' THEN 2
          WHEN '36-45' THEN 3
          WHEN '46-55' THEN 4
          WHEN '56-65' THEN 5
          WHEN '65+' THEN 6
          ELSE 7
        END
    `);

    console.log('📅 Démographie - Âge:');
    ageStats.rows.forEach(age => {
      console.log(`   - ${age.range}: ${age.count} (${age.percentage}%)`);
    });
    console.log('');

    // Top villes
    const topCities = await pool.query(`
      SELECT
        city,
        COUNT(*) as count,
        ROUND((COUNT(*)::DECIMAL / (SELECT COUNT(*) FROM users WHERE role = 'CLIENT')) * 100, 2) as percentage
      FROM users
      WHERE role = 'CLIENT' AND city IS NOT NULL AND city != ''
      GROUP BY city
      ORDER BY count DESC
      LIMIT 10
    `);

    console.log('📍 Top villes:');
    topCities.rows.forEach((city, index) => {
      console.log(`   ${index + 1}. ${city.city}: ${city.count} (${city.percentage}%)`);
    });
    console.log('');

    console.log('✅ Test terminé !');
    console.log('\n📝 Pour tester l\'API complète:');
    console.log('   1. Connectez-vous à l\'application avec un compte admin');
    console.log('   2. Ouvrez la console du navigateur (F12)');
    console.log('   3. Allez sur la page Dashboard admin');
    console.log('   4. Vérifiez que les statistiques s\'affichent correctement');
    console.log('\n   Ou utilisez curl/Postman:');
    console.log('   GET http://localhost:4000/api/admin/statistics');
    console.log('   Header: Authorization: Bearer <votre_token_admin>');

  } catch (error) {
    console.error('❌ Erreur:', error.message);
    console.error(error);
    process.exit(1);
  } finally {
    await pool.end();
  }
}

testStatisticsAPI();
