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

async function countTicketsByPrize() {
  try {
    console.log('\n📊 COMPTAGE DES TICKETS PAR LOT\n');

    const result = await pool.query(`
      SELECT
        p.name as lot_name,
        p.type as lot_type,
        COUNT(t.id) as nombre_tickets,
        ROUND((COUNT(t.id)::numeric / (SELECT COUNT(*) FROM tickets) * 100), 2) as pourcentage
      FROM prizes p
      LEFT JOIN tickets t ON p.id = t.prize_id
      GROUP BY p.id, p.name, p.type
      ORDER BY nombre_tickets DESC
    `);

    console.log('┌─────────────────────────────────────────────────────────────┐');
    result.rows.forEach(row => {
      const count = parseInt(row.nombre_tickets).toLocaleString('fr-FR');
      const percent = row.pourcentage || '0';
      console.log(`│ ${row.lot_name.padEnd(35)} ${count.padStart(10)} (${percent}%)`.padEnd(61) + '│');
    });
    console.log('└─────────────────────────────────────────────────────────────┘');

    const total = await pool.query('SELECT COUNT(*) as total FROM tickets');
    console.log(`\n📦 TOTAL : ${parseInt(total.rows[0].total).toLocaleString('fr-FR')} tickets\n`);

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

countTicketsByPrize();
