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

const fixValidatedTickets = async () => {
  try {
    console.log('\n🔧 CORRECTION DES TICKETS AVEC STATUS INVALIDE\n');

    // D'abord, vérifier s'il y a des tickets avec un status invalide
    console.log('📊 Recherche des tickets avec status invalide...\n');

    const checkResult = await pool.query(`
      SELECT id, code, status, validated_at, claimed_at
      FROM tickets
      WHERE status::text NOT IN ('PENDING', 'CLAIMED', 'REJECTED')
         OR status IS NULL
      LIMIT 10
    `);

    if (checkResult.rows.length === 0) {
      console.log('✅ Aucun ticket avec status invalide trouvé.');
      console.log('✅ La base de données est cohérente.\n');
      await pool.end();
      process.exit(0);
    }

    console.log(`⚠️  ${checkResult.rows.length} ticket(s) avec status invalide trouvé(s):\n`);
    checkResult.rows.forEach(ticket => {
      console.log(`   - ${ticket.code}: status = ${ticket.status || 'NULL'}`);
    });
    console.log('');

    // Compter le total
    const countResult = await pool.query(`
      SELECT COUNT(*) as total
      FROM tickets
      WHERE status::text NOT IN ('PENDING', 'CLAIMED', 'REJECTED')
         OR status IS NULL
    `);

    const total = parseInt(countResult.rows[0].total);
    console.log(`📊 Total de tickets à corriger: ${total}\n`);

    if (total === 0) {
      console.log('✅ Aucune correction nécessaire.\n');
      await pool.end();
      process.exit(0);
    }

    // Corriger les tickets:
    // - Si validated_at ou claimed_at existe -> CLAIMED
    // - Sinon -> PENDING
    console.log('🔄 Correction en cours...\n');

    const updateResult = await pool.query(`
      UPDATE tickets
      SET status = CASE
        WHEN validated_at IS NOT NULL OR claimed_at IS NOT NULL THEN 'CLAIMED'::ticket_status
        ELSE 'PENDING'::ticket_status
      END
      WHERE status::text NOT IN ('PENDING', 'CLAIMED', 'REJECTED')
         OR status IS NULL
    `);

    console.log(`✅ ${updateResult.rowCount} ticket(s) corrigé(s)!\n`);

    // Vérifier le résultat
    const finalCheck = await pool.query(`
      SELECT status, COUNT(*) as count
      FROM tickets
      GROUP BY status
      ORDER BY status
    `);

    console.log('📊 Répartition finale des tickets:\n');
    finalCheck.rows.forEach(row => {
      const statusLabel = row.status || 'NULL';
      console.log(`   ${statusLabel.padEnd(12)}: ${row.count}`);
    });
    console.log('');

    console.log('🎉 Correction terminée avec succès!\n');

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

fixValidatedTickets();
