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

async function runMigration() {
  try {
    console.log('🚀 Starting database migration...');
    
    // Read the migration file
    const migrationPath = path.join(__dirname, 'src/migrations/001_initial_schema.sql');
    const migrationSQL = fs.readFileSync(migrationPath, 'utf8');
    
    console.log('📄 Migration file loaded successfully');
    
    // Execute the migration
    const result = await database.query(migrationSQL);
    
    console.log('✅ Migration completed successfully!');
    console.log('📊 Migration result:', result.rows);
    
    // Verify tables were created
    const tablesQuery = `
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = 'public' 
      AND table_name IN ('templates', 'template_features', 'custom_features', 'feature_usage')
      ORDER BY table_name;
    `;
    
    const tablesResult = await database.query(tablesQuery);
    console.log('📋 Created tables:', tablesResult.rows.map(row => row.table_name));
    
    process.exit(0);
  } catch (error) {
    console.error('❌ Migration failed:', error.message);
    console.error('📚 Error details:', error);
    process.exit(1);
  }
}

runMigration();
