#!/usr/bin/env node

// Setup module path to include backend node_modules
const path = require('path');
const backendPath = path.join(__dirname, '..', 'backend');
process.env.NODE_PATH = path.join(backendPath, 'node_modules') + ':' + (process.env.NODE_PATH || '');
require('module').Module._initPaths();

const mongoose = require('mongoose');
const CouchDBSetup = require('./setup-couchdb');
const MongoToCouchMigrator = require('./migrate-to-couchdb');

class ProductionMigration {
  constructor() {
    this.setup = new CouchDBSetup();
    this.migrator = new MongoToCouchMigrator();
  }

  async run() {
    console.log('🚀 Starting production setup for CouchDB...\n');
    
    try {
      // Step 1: Setup CouchDB
      console.log('=== Step 1: Setting up CouchDB ===');
      await this.setup.initialize();
      await this.setup.createDatabase();
      await this.setup.createIndexes();
      await this.setup.createSecurityDocument();
      await this.setup.seedBadges();
      console.log('✅ CouchDB setup completed\n');
      
      // Step 2: Optional - Migrate data from MongoDB if available
      if (process.env.MONGO_URI && process.env.MIGRATE_FROM_MONGO === 'true') {
        console.log('=== Step 2: Migrating data from MongoDB ===');
        await this.migrator.runMigration();
        console.log('✅ Data migration completed\n');
      } else {
        console.log('ℹ️  Skipping MongoDB migration (not requested or no MONGO_URI provided)\n');
      }
      
      // Step 3: Final verification
      console.log('=== Step 3: Final verification ===');
      await this.setup.verifySetup();
      console.log('✅ Verification completed\n');
      
      console.log('🎉 Production setup completed successfully!');
      console.log('\n📋 Next steps:');
      console.log('1. Update your application configuration to use CouchDB');
      console.log('2. Deploy the updated application');
      console.log('3. Monitor the application for any issues');
      
    } catch (error) {
      console.error('\n❌ Production setup failed:', error.message);
      console.error('\n📋 Troubleshooting steps:');
      console.error('1. Verify CouchDB is running and accessible');
      console.error('2. Check environment variables and credentials');
      console.error('3. Review setup logs for specific errors');
      
      process.exit(1);
    }
  }
}

// Run migration if called directly
if (require.main === module) {
  const migration = new ProductionMigration();
  migration.run().catch(console.error);
}

module.exports = ProductionMigration;