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

async function runMigrations() {
  console.log('🚀 Starting Template Manager database migration...');
  
  try {
    // Get all migration files in order
    const migrationFiles = [
      '001_initial_schema.sql',
      '002_admin_approval_workflow.sql',
      '003_custom_templates.sql',
      '004_add_is_custom_flag.sql',
      '004_add_user_id_to_custom_templates.sql',
      '005_fix_custom_features_foreign_key.sql'
    ];
    
    for (const migrationFile of migrationFiles) {
      const migrationPath = path.join(__dirname, migrationFile);
      
      // Check if migration file exists
      if (!fs.existsSync(migrationPath)) {
        console.log(`Migration file not found: ${migrationFile}`);
        continue;
      }
      
      console.log(`Running migration: ${migrationFile}`);
      
      const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
      
      // Execute the migration
      await database.query(migrationSQL);
      
      console.log(`Migration ${migrationFile} completed successfully!`);
    }
    
    console.log('All migrations completed successfully!');
    
    // Verify tables were created
    const result = await database.query(`
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      AND table_name IN ('templates', 'template_features', 'feature_usage', 'custom_features', 'custom_templates', 'feature_synonyms', 'admin_notifications')
      ORDER BY table_name
    `);
    
    console.log('Verified tables:', result.rows.map(row => row.table_name));
    
  } catch (error) {
    console.error('Migration failed:', error.message);
    process.exit(1);
  } finally {
    await database.close();
  }
}

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

module.exports = { runMigrations };