import pkg from "pg";
const { Pool } = pkg;

// Configuration de la base de données
const pool = new Pool({
  host: "51.75.24.29",
  port: 5433,
  user: "postgres",
  password: "postgres",
  database: "thetiptop_dev",
});

async function displayAdminTickets() {
  try {
    console.log('🎫 GESTION DES TICKETS - INTERFACE ADMIN\n');
    console.log('━'.repeat(80));

    // Récupérer tous les tickets avec leurs détails
    const ticketsResult = await pool.query(`
      SELECT
        t.id,
        t.code,
        t.status,
        t.played_at,
        t.claimed_at,
        t.validated_at,
        t.rejection_reason,
        u.email as user_email,
        u.first_name || ' ' || u.last_name as user_name,
        u.phone as user_phone,
        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
      JOIN users u ON t.user_id = u.id
      JOIN prizes p ON t.prize_id = p.id
      LEFT JOIN users v ON t.validated_by = v.id
      ORDER BY t.played_at DESC
    `);

    const tickets = ticketsResult.rows;

    // Statistiques globales
    const stats = {
      total: tickets.length,
      pending: tickets.filter(t => t.status === 'PENDING').length,
      claimed: tickets.filter(t => t.status === 'CLAIMED').length,
      rejected: tickets.filter(t => t.status === 'REJECTED').length,
    };

    console.log('📊 STATISTIQUES GLOBALES');
    console.log('━'.repeat(80));
    console.log(`   Total de tickets: ${stats.total}`);
    console.log(`   ⏳ En attente (PENDING): ${stats.pending}`);
    console.log(`   ✅ Validés (CLAIMED): ${stats.claimed}`);
    console.log(`   ❌ Rejetés (REJECTED): ${stats.rejected}`);
    console.log('━'.repeat(80));

    // Afficher les tickets par statut
    console.log('\n📋 TICKETS EN ATTENTE (PENDING)\n');
    const pendingTickets = tickets.filter(t => t.status === 'PENDING');

    if (pendingTickets.length === 0) {
      console.log('   Aucun ticket en attente\n');
    } else {
      pendingTickets.forEach((ticket, index) => {
        console.log(`${index + 1}. Code: ${ticket.code}`);
        console.log(`   Client: ${ticket.user_name} (${ticket.user_email})`);
        console.log(`   Téléphone: ${ticket.user_phone || 'N/A'}`);
        console.log(`   Prix: ${ticket.prize_name} - ${ticket.prize_value}€`);
        console.log(`   Type: ${ticket.prize_type}`);
        console.log(`   Joué le: ${new Date(ticket.played_at).toLocaleString('fr-FR')}`);
        console.log('   ' + '─'.repeat(76));
      });
    }

    console.log('\n✅ TICKETS VALIDÉS (CLAIMED)\n');
    const claimedTickets = tickets.filter(t => t.status === 'CLAIMED');

    if (claimedTickets.length === 0) {
      console.log('   Aucun ticket validé\n');
    } else {
      claimedTickets.forEach((ticket, index) => {
        console.log(`${index + 1}. Code: ${ticket.code}`);
        console.log(`   Client: ${ticket.user_name} (${ticket.user_email})`);
        console.log(`   Prix: ${ticket.prize_name} - ${ticket.prize_value}€`);
        console.log(`   Validé le: ${new Date(ticket.validated_at).toLocaleString('fr-FR')}`);
        console.log(`   Validé par: ${ticket.validated_by_name || 'N/A'}`);
        console.log('   ' + '─'.repeat(76));
      });
    }

    console.log('\n❌ TICKETS REJETÉS (REJECTED)\n');
    const rejectedTickets = tickets.filter(t => t.status === 'REJECTED');

    if (rejectedTickets.length === 0) {
      console.log('   Aucun ticket rejeté\n');
    } else {
      rejectedTickets.forEach((ticket, index) => {
        console.log(`${index + 1}. Code: ${ticket.code}`);
        console.log(`   Client: ${ticket.user_name} (${ticket.user_email})`);
        console.log(`   Prix: ${ticket.prize_name}`);
        console.log(`   Raison du rejet: ${ticket.rejection_reason || 'Non spécifiée'}`);
        console.log(`   Rejeté le: ${new Date(ticket.validated_at).toLocaleString('fr-FR')}`);
        console.log(`   Rejeté par: ${ticket.validated_by_name || 'N/A'}`);
        console.log('   ' + '─'.repeat(76));
      });
    }

    // Statistiques par type de prix
    console.log('\n🎁 RÉPARTITION PAR TYPE DE PRIX\n');
    const prizeTypes = {};
    tickets.forEach(ticket => {
      if (!prizeTypes[ticket.prize_type]) {
        prizeTypes[ticket.prize_type] = 0;
      }
      prizeTypes[ticket.prize_type]++;
    });

    Object.entries(prizeTypes).forEach(([type, count]) => {
      const percentage = ((count / tickets.length) * 100).toFixed(1);
      console.log(`   ${type}: ${count} tickets (${percentage}%)`);
    });

    console.log('\n━'.repeat(80));
    console.log('✅ Fin du rapport\n');

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

displayAdminTickets();
