const { spawn } = require('child_process');
const path = require('path');

console.log('🔄 Restarting backend server with updated rate limiting...');

// Kill any existing node processes
const killProcess = spawn('taskkill', ['/f', '/im', 'node.exe'], { 
  stdio: 'inherit',
  shell: true 
});

killProcess.on('close', (code) => {
  console.log('✅ Killed existing processes');
  
  // Wait a moment then start the server
  setTimeout(() => {
    console.log('🚀 Starting backend server...');
    
    const serverProcess = spawn('npm', ['run', 'dev'], {
      cwd: path.join(__dirname),
      stdio: 'inherit',
      shell: true
    });
    
    serverProcess.on('error', (err) => {
      console.error('❌ Failed to start server:', err);
    });
    
    serverProcess.on('close', (code) => {
      console.log(`Server process exited with code ${code}`);
    });
  }, 2000);
});

killProcess.on('error', (err) => {
  console.log('No existing processes to kill, starting server...');
  
  const serverProcess = spawn('npm', ['run', 'dev'], {
    cwd: path.join(__dirname),
    stdio: 'inherit',
    shell: true
  });
  
  serverProcess.on('error', (err) => {
    console.error('❌ Failed to start server:', err);
  });
});
