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

// Function to run a command in a specific directory
function runCommand(command, args, cwd, name) {
  return new Promise((resolve, reject) => {
    const process = spawn(command, args, {
      cwd,
      stdio: 'inherit'
    });

    process.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`${name} process exited with code ${code}`));
      }
    });

    process.on('error', (err) => {
      reject(new Error(`${name} process failed: ${err.message}`));
    });
  });
}

// Main function to start both servers
async function startServers() {
  console.log('Starting Astro Redi development servers...\n');

  try {
    // Start both servers concurrently
    await Promise.all([
      runCommand('bun', ['run', 'dev'], path.join(__dirname, '../frontend'), 'Frontend'),
      runCommand('pocketbase', ['serve', '--http=127.0.0.1:8090'], path.join(__dirname, '../backend'), 'Backend')
    ]);

    console.log('\nBoth servers started successfully!');
  } catch (error) {
    console.error('Error starting servers:', error.message);
    process.exit(1);
  }
}

// Handle graceful shutdown
process.on('SIGINT', () => {
  console.log('\nShutting down servers...');
  process.exit(0);
});

// Start the servers
startServers();