import { pool } from '../db.js';

async function testAPIFilter() {
  try {
    console.log('\n🧪 TEST DU FILTRAGE API\n');

    // Test 1: Sans filtre - Tous les tickets
    console.log('1️⃣ Sans filtre:');
    const allTickets = await pool.query(`
      SELECT
        t.code,
        p.name as prize_name,
        p.type as prize_type,
        t.status
      FROM tickets t
      LEFT JOIN prizes p ON t.prize_id = p.id
      LIMIT 5
    `);
    console.log(`   ${allTickets.rows.length} résultats`);
    allTickets.rows.forEach((t, idx) => {
      console.log(`   ${idx + 1}. ${t.code} - ${t.prize_name} (${t.prize_type})`);
    });

    // Test 2: Avec filtre prizeType = INFUSEUR
    console.log('\n2️⃣ Filtre prizeType=INFUSEUR:');
    const infuseurTickets = await pool.query(`
      SELECT
        t.code,
        p.name as prize_name,
        p.type as prize_type,
        t.status
      FROM tickets t
      LEFT JOIN prizes p ON t.prize_id = p.id
      WHERE p.type = $1
      LIMIT 5
    `, ['INFUSEUR']);
    console.log(`   ${infuseurTickets.rows.length} résultats`);
    infuseurTickets.rows.forEach((t, idx) => {
      console.log(`   ${idx + 1}. ${t.code} - ${t.prize_name} (${t.prize_type})`);
    });

    // Test 3: Compter les tickets par type
    console.log('\n3️⃣ Comptage par type:');
    const count = await pool.query(`
      SELECT
        p.type,
        p.name,
        COUNT(t.id) as total
      FROM prizes p
      LEFT JOIN tickets t ON p.id = t.prize_id
      GROUP BY p.type, p.name
      ORDER BY total DESC
    `);
    count.rows.forEach(row => {
      console.log(`   ${row.type}: ${row.name} (${row.total} tickets)`);
    });

    // Test 4: Vérifier si des tickets ont été joués
    console.log('\n4️⃣ Tickets joués:');
    const played = await pool.query(`
      SELECT COUNT(*) as total
      FROM tickets
      WHERE user_id IS NOT NULL
    `);
    console.log(`   Total tickets joués: ${played.rows[0].total}`);

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

testAPIFilter();
