require('dotenv').config();
const connectDB = require('../config/database');
const migrationHelper = require('../utils/migrationHelper');

/**
 * Rollback một migration cụ thể
 */
async function rollbackMigration(migrationName) {
  const mongoose = require('mongoose');
  let ownConn = false;
  
  try {
    const wasConnected = mongoose.connection.readyState === 1;
    await connectDB();
    if (!wasConnected) ownConn = true;
    
    const hasRun = await migrationHelper.hasRun(migrationName);
    if (!hasRun) {
      console.log(`⚠️  Migration "${migrationName}" chưa được chạy, không thể rollback.`);
      if (ownConn && mongoose.connection.readyState === 1) {
        await mongoose.disconnect();
      }
      process.exit(0);
    }
    
    const result = await migrationHelper.rollback(migrationName);
    if (result) {
      console.log(`✅ Đã rollback migration: ${migrationName}`);
    } else {
      console.log(`❌ Không thể rollback migration: ${migrationName}`);
    }
    
    if (ownConn && mongoose.connection.readyState === 1) {
      await mongoose.disconnect();
    }
  } catch (error) {
    console.error('❌ Lỗi:', error.message);
    if (ownConn && mongoose.connection.readyState === 1) {
      await mongoose.disconnect();
    }
    process.exit(1);
  }
}

/**
 * Rollback batch cuối cùng
 */
async function rollbackLastBatch() {
  const mongoose = require('mongoose');
  let ownConn = false;
  
  try {
    const wasConnected = mongoose.connection.readyState === 1;
    await connectDB();
    if (!wasConnected) ownConn = true;
    
    const lastBatch = await migrationHelper.getLastBatch();
    if (lastBatch === 0) {
      console.log('⚠️  Không có batch nào để rollback.');
      if (ownConn && mongoose.connection.readyState === 1) {
        await mongoose.disconnect();
      }
      process.exit(0);
    }
    
    const migrations = await migrationHelper.getMigrationsByBatch(lastBatch);
    if (migrations.length === 0) {
      console.log(`⚠️  Batch ${lastBatch} không có migration nào.`);
      if (ownConn && mongoose.connection.readyState === 1) {
        await mongoose.disconnect();
      }
      process.exit(0);
    }
    
    console.log(`\n🔄 Đang rollback batch ${lastBatch}...`);
    console.log(`📋 Các migration sẽ được rollback:`);
    migrations.forEach(m => {
      console.log(`   - ${m.name}`);
    });
    
    const deletedCount = await migrationHelper.rollbackBatch(lastBatch);
    console.log(`\n✅ Đã rollback ${deletedCount} migration(s) trong batch ${lastBatch}`);
    
    if (ownConn && mongoose.connection.readyState === 1) {
      await mongoose.disconnect();
    }
  } catch (error) {
    console.error('❌ Lỗi:', error.message);
    if (ownConn && mongoose.connection.readyState === 1) {
      await mongoose.disconnect();
    }
    process.exit(1);
  }
}

// Xử lý command line arguments
const args = process.argv.slice(2);

if (args.length === 0) {
  console.log('Usage:');
  console.log('  node scripts/migrate-rollback.js <migration-name>  - Rollback một migration cụ thể');
  console.log('  node scripts/migrate-rollback.js --batch           - Rollback batch cuối cùng');
  process.exit(0);
}

if (args[0] === '--batch') {
  rollbackLastBatch();
} else {
  rollbackMigration(args[0]);
}

