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

const rootDir = path.resolve(__dirname, '..');
const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';

const commands = [
  {
    name: 'backend',
    cwd: path.join(rootDir, 'backend'),
    args: ['run', 'dev']
  },
  {
    name: 'frontend',
    cwd: path.join(rootDir, 'semillero'),
    args: ['start']
  }
];

const children = [];
let shuttingDown = false;

const stopAll = (exitCode = 0) => {
  if (shuttingDown) return;
  shuttingDown = true;

  for (const child of children) {
    if (!child.killed) {
      child.kill('SIGTERM');
    }
  }

  setTimeout(() => process.exit(exitCode), 300);
};

for (const command of commands) {
  const child = spawn(npmCmd, command.args, {
    cwd: command.cwd,
    env: process.env,
    stdio: 'inherit',
    shell: false
  });

  children.push(child);

  child.on('exit', (code, signal) => {
    if (shuttingDown) return;
    if (code === 0 || signal) {
      console.log(`[dev] ${command.name} finalizo.`);
      stopAll(0);
      return;
    }

    console.error(`[dev] ${command.name} fallo con codigo ${code}.`);
    stopAll(code || 1);
  });
}

process.once('SIGINT', () => stopAll(0));
process.once('SIGTERM', () => stopAll(0));
