// require('dotenv').config();
// const fs = require('fs');
// const path = require('path');
// const database = require('../config/database');

// async function runMigrations() {
//   console.log('🚀 Starting User Auth database migration...');
  
//   try {
//     // Read the SQL migration file
//     const migrationPath = path.join(__dirname, '001_user_auth_schema.sql');
//     const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
    
//     console.log('📄 Running migration: 001_user_auth_schema.sql');
    
//     // Execute the migration
//     await database.query(migrationSQL);
    
//     console.log('✅ User Auth migration completed successfully!');
//     console.log('📊 Database schema created:');
//     console.log('   - users table (with admin and test users)');
//     console.log('   - refresh_tokens table');
//     console.log('   - user_sessions table');
//     console.log('   - user_feature_preferences table');
//     console.log('   - user_projects table');
//     console.log('   - indexes and triggers');
//     console.log('   - cleanup functions');
    
//     // Verify tables were created
//     const result = await database.query(`
//       SELECT 
//         schemaname,
//         tablename,
//         tableowner
//       FROM pg_tables 
//       WHERE schemaname = 'public' 
//       AND tablename IN ('users', 'refresh_tokens', 'user_sessions', 'user_feature_preferences', 'user_projects')
//       ORDER BY tablename
//     `);
    
//     console.log('🔍 Verified tables:');
//     result.rows.forEach(row => {
//       console.log(`   - ${row.tablename} (owner: ${row.tableowner})`);
//     });
    
//     // Test initial users
//     const userCount = await database.query('SELECT COUNT(*) as count FROM users');
//     console.log(`👥 Initial users created: ${userCount.rows[0].count}`);
    
//     console.log('🔐 Default credentials:');
//     console.log('   Admin: admin@tech4biz.com / admin123');
//     console.log('   Test:  test@tech4biz.com / admin123');
//     console.log('   ⚠️  Change passwords in production!');
    
//   } catch (error) {
//     console.error('❌ Migration failed:', error.message);
//     console.error('📍 Error details:', error);
//     process.exit(1);
//   } finally {
//     await database.close();
//   }
// }

// // Run migration if called directly
// if (require.main === module) {
//   runMigrations();
// }

// module.exports = { runMigrations };

require('dotenv').config();
const fs = require('fs');
const path = require('path');
const database = require('../config/database');

async function runMigrations() {
  console.log('🚀 Starting database migrations...');
  
  const migrations = [
    '001_user_auth_schema.sql',
    '002_email_verification_schema.sql'
  ];
  
  try {
    // Ensure required extensions exist before running migrations
    console.log('🔧 Ensuring required PostgreSQL extensions...');
    await database.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";');
    console.log('✅ Extensions ready');

    for (const migrationFile of migrations) {
      const migrationPath = path.join(__dirname, migrationFile);
      if (!fs.existsSync(migrationPath)) {
        console.warn(`⚠️ Migration file ${migrationFile} not found, skipping...`);
        continue;
      }
      
      const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
      console.log(`📄 Running migration: ${migrationFile}`);
      
      await database.query(migrationSQL);
      console.log(`✅ Migration ${migrationFile} completed!`);
    }
    
    // Verify all tables
    const result = await database.query(`
      SELECT 
        schemaname,
        tablename,
        tableowner
      FROM pg_tables 
      WHERE schemaname = 'public' 
      AND tablename IN ('users', 'refresh_tokens', 'user_sessions', 'user_feature_preferences', 'user_projects', 'email_verification_tokens')
      ORDER BY tablename
    `);
    
    console.log('🔍 Verified tables:');
    result.rows.forEach(row => {
      console.log(`   - ${row.tablename} (owner: ${row.tableowner})`);
    });
    
  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('📍 Error details:', error);
    process.exit(1);
  } finally {
    await database.close();  // Close connection via Database wrapper
  }
}

// Run migration if called directly
if (require.main === module) {
  runMigrations();
}

module.exports = { runMigrations };