const { query, pool } = require('./config/database');
const fs = require('fs');

async function applyFixes() {
  console.log('🔧 Applying database fixes...\n');
  
  try {
    const sql = fs.readFileSync('./fix-database-issues.sql', 'utf8');
    
    console.log('Executing SQL fixes...');
    await query(sql);
    
    console.log('\n✅ All fixes applied successfully!\n');
    
    // Verify the fixes
    console.log('📊 Verifying fixes:');
    
    // Count indexes
    const indexes = await query(`
      SELECT COUNT(*) as count 
      FROM pg_indexes 
      WHERE schemaname = 'public'
    `);
    console.log(`  • Total indexes: ${indexes.rows[0].count}`);
    
    // Check constraints
    const constraints = await query(`
      SELECT COUNT(*) as count 
      FROM information_schema.table_constraints 
      WHERE table_schema = 'public'
    `);
    console.log(`  • Total constraints: ${constraints.rows[0].count}`);
    
    // Check triggers
    const triggers = await query(`
      SELECT COUNT(*) as count 
      FROM information_schema.triggers 
      WHERE trigger_schema = 'public'
    `);
    console.log(`  • Total triggers: ${triggers.rows[0].count}`);
    
    console.log('\n🎉 Database optimization complete!\n');
    process.exit(0);
  } catch (error) {
    console.error('❌ Error applying fixes:', error.message);
    console.error('Details:', error);
    process.exit(1);
  }
}

applyFixes();
