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

const fixTicketStatus = async () => {
  try {
    console.log('🔄 Correction du statut des tickets non réclamés...\n');

    // Mettre à NULL le statut des tickets qui n'ont pas de user_id
    // (tickets pré-générés, non encore joués)
    const result = await pool.query(`
      UPDATE tickets
      SET status = NULL, played_at = NULL
      WHERE user_id IS NULL AND status = 'PENDING'
      RETURNING id
    `);

    const count = result.rowCount;
    console.log(`✅ ${count.toLocaleString('fr-FR')} tickets mis à jour`);
    console.log('   Status: NULL (disponible, non encore joué)');
    console.log('   played_at: NULL\n');

    // Afficher les statistiques
    const stats = await pool.query(`
      SELECT
        status,
        COUNT(*) as count,
        CASE
          WHEN user_id IS NULL THEN 'Sans utilisateur'
          ELSE 'Avec utilisateur'
        END as user_status
      FROM tickets
      GROUP BY status, CASE WHEN user_id IS NULL THEN 'Sans utilisateur' ELSE 'Avec utilisateur' END
      ORDER BY status NULLS FIRST, user_status
    `);

    console.log('📊 STATISTIQUES DES TICKETS:');
    stats.rows.forEach(row => {
      const statusLabel = row.status || 'NULL (disponible)';
      const countStr = parseInt(row.count).toLocaleString('fr-FR');
      console.log(`  • ${statusLabel} | ${row.user_status}: ${countStr}`);
    });
    console.log('');

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

fixTicketStatus();
