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

async function syncPrizeStocks() {
  try {
    console.log('\n🔄 SYNCHRONISATION DES STOCKS\n');

    // Compter les tickets par prize_id
    const ticketCounts = await pool.query(`
      SELECT
        prize_id,
        COUNT(*) as ticket_count
      FROM tickets
      GROUP BY prize_id
    `);

    console.log('📊 Mise à jour des stocks...\n');

    for (const row of ticketCounts.rows) {
      const { prize_id, ticket_count } = row;

      // Récupérer les infos du prize
      const prizeInfo = await pool.query(
        'SELECT name, stock FROM prizes WHERE id = $1',
        [prize_id]
      );

      if (prizeInfo.rows.length > 0) {
        const oldStock = prizeInfo.rows[0].stock;
        const newStock = parseInt(ticket_count);

        // Mettre à jour le stock
        await pool.query(
          'UPDATE prizes SET stock = $1 WHERE id = $2',
          [newStock, prize_id]
        );

        console.log(`✅ ${prizeInfo.rows[0].name}`);
        console.log(`   Ancien stock: ${oldStock}`);
        console.log(`   Nouveau stock: ${newStock}`);
        console.log('');
      }
    }

    // Afficher le résultat final
    const finalResult = await pool.query(`
      SELECT
        p.name,
        p.type,
        p.stock,
        COUNT(t.id) as tickets_count
      FROM prizes p
      LEFT JOIN tickets t ON p.id = t.prize_id
      GROUP BY p.id, p.name, p.type, p.stock
      ORDER BY tickets_count DESC
    `);

    console.log('📦 RÉSUMÉ FINAL:\n');
    console.log('┌───────────────────────────────────────────────────────────┐');
    finalResult.rows.forEach(row => {
      const name = row.name.padEnd(35);
      const stock = row.stock.toString().padStart(10);
      const tickets = row.tickets_count.toString().padStart(10);
      console.log(`│ ${name} Stock: ${stock} | Tickets: ${tickets} │`);
    });
    console.log('└───────────────────────────────────────────────────────────┘\n');

    console.log('✅ Synchronisation terminée!\n');
    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('❌ Erreur:', error.message);
    await pool.end();
    process.exit(1);
  }
}

syncPrizeStocks();
