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

async function testFinalFilter() {
  try {
    console.log('\n🔥 TEST FINAL DU FILTRAGE\n');

    // Simuler exactement ce que fait le controller
    const prizeType = 'INFUSEUR';
    const page = 1;
    const limit = 20;
    const offset = (page - 1) * limit;

    let query = `
      SELECT
        t.id,
        t.code,
        t.status,
        t.played_at,
        t.claimed_at,
        t.validated_at,
        t.created_at,
        u.email as user_email,
        u.first_name || ' ' || u.last_name as user_name,
        p.name as prize_name,
        p.type as prize_type,
        p.value as prize_value,
        v.first_name || ' ' || v.last_name as validated_by_name
      FROM tickets t
      LEFT JOIN users u ON t.user_id = u.id
      LEFT JOIN prizes p ON t.prize_id = p.id
      LEFT JOIN users v ON t.validated_by = v.id
    `;

    const params = [];
    let paramCount = 1;
    const whereClauses = [];

    // Filtre par type de lot
    if (prizeType) {
      whereClauses.push(`p.type = $${paramCount++}`);
      params.push(prizeType);
    }

    // Ajouter les clauses WHERE si nécessaire
    if (whereClauses.length > 0) {
      query += ' WHERE ' + whereClauses.join(' AND ');
    }

    query += ` ORDER BY t.played_at DESC NULLS LAST, t.created_at DESC LIMIT $${paramCount++} OFFSET $${paramCount}`;
    params.push(limit, offset);

    console.log('📝 Requête SQL:');
    console.log(query);
    console.log('\n📝 Paramètres:', params);

    const result = await pool.query(query, params);

    console.log(`\n✅ ${result.rows.length} tickets trouvés\n`);

    if (result.rows.length > 0) {
      console.log('🎫 Les 5 premiers tickets:');
      result.rows.slice(0, 5).forEach((t, idx) => {
        console.log(`  ${idx + 1}. ${t.code} - ${t.prize_name} (${t.prize_type})`);
      });
    } else {
      console.log('❌ AUCUN TICKET TROUVÉ !');
    }

    // Vérifier si on a bien des INFUSEUR
    const allInfuseur = result.rows.every(t => t.prize_type === 'INFUSEUR');

    if (allInfuseur && result.rows.length > 0) {
      console.log('\n✅ SUCCÈS: Tous les tickets sont bien des INFUSEUR');
    } else if (result.rows.length > 0) {
      console.log('\n❌ ÉCHEC: Les tickets ne sont PAS tous des INFUSEUR');
      const types = [...new Set(result.rows.map(t => t.prize_type))];
      console.log('   Types trouvés:', types);
    }

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

testFinalFilter();
