import 'dotenv/config';
import { pool } from '../db.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function applyMigration() {
  console.log('🔧 Application de la migration: add-prize-delivery-tracking\n');

  try {
    // Lire le fichier SQL
    const migrationPath = path.join(__dirname, '../database/migrations/add-prize-delivery-tracking.sql');
    const migrationSQL = fs.readFileSync(migrationPath, 'utf8');

    // Vérifier l'état actuel
    console.log('📋 Vérification de l\'état actuel de la base de données...\n');

    const columnsCheck = await pool.query(`
      SELECT column_name
      FROM information_schema.columns
      WHERE table_name = 'tickets'
      AND column_name IN ('delivered_at', 'delivered_by', 'delivery_notes')
    `);

    console.log('📊 État actuel:');
    console.log(`  • Colonnes existantes: ${columnsCheck.rows.map(r => r.column_name).join(', ') || 'Aucune'}`);

    // Appliquer la migration
    console.log('\n🚀 Application de la migration...\n');
    await pool.query(migrationSQL);

    // Vérifier le nouvel état
    const newColumnsCheck = await pool.query(`
      SELECT column_name, data_type
      FROM information_schema.columns
      WHERE table_name = 'tickets'
      AND column_name IN ('delivered_at', 'delivered_by', 'delivery_notes')
      ORDER BY ordinal_position
    `);

    console.log('✅ Migration appliquée avec succès!\n');

    console.log('📊 Nouvel état:');
    newColumnsCheck.rows.forEach(col => {
      console.log(`  • ${col.column_name}: ${col.data_type}`);
    });

    // Statistiques
    const stats = await pool.query(`
      SELECT
        COUNT(*) as total_tickets,
        COUNT(CASE WHEN delivered_at IS NOT NULL THEN 1 END) as delivered_tickets
      FROM tickets
    `);

    console.log('\n📈 Statistiques:');
    console.log(`  • Total tickets: ${stats.rows[0].total_tickets}`);
    console.log(`  • Tickets livrés: ${stats.rows[0].delivered_tickets}`);

    console.log('\n✨ Migration terminée!');

  } catch (error) {
    console.error('❌ Erreur lors de l\'application de la migration:', error);
    throw error;
  } finally {
    await pool.end();
  }
}

applyMigration();
