const mongoose = require('mongoose');
const logger = require('../utils/logger');
require('dotenv').config();

async function migrate() {
  try {
    logger.info('Starting database migration...');
    
    // Connect to database
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/galaxystrikeonline');
    
    logger.info('Connected to database');
    
    // Create indexes for performance
    const db = mongoose.connection.db;
    
    // Player indexes
    await db.collection('players').createIndex({ userId: 1 }, { unique: true });
    await db.collection('players').createIndex({ email: 1 }, { unique: true });
    await db.collection('players').createIndex({ 'stats.level': 1 });
    await db.collection('players').createIndex({ currentServer: 1 });
    
    // Ship indexes
    await db.collection('ships').createIndex({ userId: 1 });
    await db.collection('ships').createIndex({ id: 1 }, { unique: true });
    await db.collection('ships').createIndex({ isEquipped: 1 });
    await db.collection('ships').createIndex({ isCurrent: 1 });
    
    // Inventory indexes
    await db.collection('inventories').createIndex({ userId: 1 }, { unique: true });
    await db.collection('inventories').createIndex({ 'items.id': 1 });
    await db.collection('inventories').createIndex({ 'items.type': 1 });
    
    logger.info('Database migration completed successfully');
    
    // Close connection
    await mongoose.connection.close();
    logger.info('Database connection closed');
    
  } catch (error) {
    logger.error('Migration failed:', error);
    process.exit(1);
  }
}

if (require.main === module) {
  migrate();
}

module.exports = migrate;
