const { execFile, spawn } = require('child_process');

function runCommand(command, args = [], options = {}) {
  return new Promise((resolve, reject) => {
    execFile(command, args, options, (error, stdout = '', stderr = '') => {
      if (error) {
        error.stdout = stdout;
        error.stderr = stderr;
        reject(error);
        return;
      }

      resolve({ stdout, stderr });
    });
  });
}

function runInteractiveCommand(command, args = [], options = {}) {
  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      cwd: options.cwd,
      env: options.env || process.env,
      stdio: options.stdio || 'inherit'
    });

    child.on('error', reject);
    child.on('close', (code, signal) => {
      if (code === 0) {
        resolve({ code, signal });
        return;
      }

      const error = new Error(`${command} ${args.join(' ')} failed with exit code ${code}`);
      error.code = code;
      error.signal = signal;
      reject(error);
    });
  });
}

module.exports = { runCommand, runInteractiveCommand };
