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

const directories = ['client', 'server'];

function runCommand(command, args, cwd) {
    const proc = spawn(command, args, { cwd, stdio: 'inherit', shell: true });
    proc.on('close', (code) => {
        if (code !== 0) {
            console.error(`Process in ${cwd} exited with code ${code}`);
        }
    });
}

directories.forEach(dir => {
    const fullPath = path.join(__dirname, dir);

    // Check if node_modules exists; if not, run npm install first
    if (!fs.existsSync(path.join(fullPath, 'node_modules'))) {
        console.log(`node_modules not found in ${dir}. Running npm install...`);
        runCommand('npm', ['install'], fullPath);
    }

    console.log(`Starting npm start in ${dir}`);
    runCommand('npm', ['start'], fullPath);
});
