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

async function testAllTicketsFilter() {
  try {
    console.log('\n🧪 TEST AFFICHAGE TOUS LES TICKETS AVEC FILTRE\n');

    // Test 1: Sans filtre - premiers 20 tickets
    console.log('1️⃣ Sans filtre (20 premiers):');
    const allTickets = await pool.query(`
      SELECT
        t.code,
        p.name as prize_name,
        p.type as prize_type,
        t.status,
        t.played_at
      FROM tickets t
      LEFT JOIN prizes p ON t.prize_id = p.id
      ORDER BY t.played_at DESC NULLS LAST, t.created_at DESC
      LIMIT 20
    `);
    console.log(`   ${allTickets.rows.length} résultats\n`);
    allTickets.rows.slice(0, 5).forEach((t, idx) => {
      const played = t.played_at ? '✓ Joué' : '○ Non joué';
      console.log(`   ${idx + 1}. ${t.code} - ${t.prize_name} (${t.prize_type}) ${played}`);
    });

    // Test 2: Filtre THE_SIGNATURE
    console.log('\n2️⃣ Filtre prizeType=THE_SIGNATURE (20 premiers):');
    const signatureTickets = await pool.query(`
      SELECT
        t.code,
        p.name as prize_name,
        p.type as prize_type,
        t.status,
        t.played_at
      FROM tickets t
      LEFT JOIN prizes p ON t.prize_id = p.id
      WHERE p.type = $1
      ORDER BY t.played_at DESC NULLS LAST, t.created_at DESC
      LIMIT 20
    `, ['THE_SIGNATURE']);
    console.log(`   ${signatureTickets.rows.length} résultats\n`);
    signatureTickets.rows.slice(0, 5).forEach((t, idx) => {
      const played = t.played_at ? '✓ Joué' : '○ Non joué';
      console.log(`   ${idx + 1}. ${t.code} - ${t.prize_name} (${t.prize_type}) ${played}`);
    });

    // Test 3: Compter avec filtre
    console.log('\n3️⃣ Comptage avec filtre THE_SIGNATURE:');
    const count = await pool.query(`
      SELECT COUNT(*) as total
      FROM tickets t
      LEFT JOIN prizes p ON t.prize_id = p.id
      WHERE p.type = $1
    `, ['THE_SIGNATURE']);
    console.log(`   Total: ${parseInt(count.rows[0].total).toLocaleString('fr-FR')} tickets`);

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

testAllTicketsFilter();
