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",
});

/**
 * Génère un code de ticket au format TTP2025ABC (10 caractères)
 */
function generateNewTicketCode(index) {
  const year = new Date().getFullYear();
  // Générer 3 caractères aléatoires alphanumériques
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let randomChars = '';
  for (let i = 0; i < 3; i++) {
    randomChars += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return `TTP${year}${randomChars}`;
}

async function updateTicketCodes() {
  try {
    console.log('🔄 Mise à jour des codes de tickets...\n');

    // Récupérer tous les tickets
    const result = await pool.query('SELECT id, code FROM tickets ORDER BY created_at');

    const tickets = result.rows;
    console.log(`📊 ${tickets.length} tickets trouvés\n`);

    if (tickets.length === 0) {
      console.log('⚠️  Aucun ticket à mettre à jour');
      await pool.end();
      return;
    }

    let updatedCount = 0;
    const newCodes = new Set(); // Pour éviter les doublons

    for (let i = 0; i < tickets.length; i++) {
      const ticket = tickets[i];
      let newCode;

      // Générer un code unique
      do {
        newCode = generateNewTicketCode(i);
      } while (newCodes.has(newCode));

      newCodes.add(newCode);

      // Mettre à jour le ticket
      await pool.query(
        'UPDATE tickets SET code = $1 WHERE id = $2',
        [newCode, ticket.id]
      );

      updatedCount++;
      console.log(`✅ [${updatedCount}/${tickets.length}] ${ticket.code} → ${newCode}`);
    }

    console.log(`\n✅ ${updatedCount} tickets mis à jour avec succès!`);
    console.log('\n📋 Exemple de nouveaux codes:');

    // Afficher quelques exemples
    const examplesResult = await pool.query('SELECT code FROM tickets LIMIT 5');
    examplesResult.rows.forEach((row, index) => {
      console.log(`   ${index + 1}. ${row.code}`);
    });

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

updateTicketCodes();
