import { spawn } from "node:child_process";

import { findPowerShell } from "./find-powershell.js";

export function invokePowerShellScript(scriptPath, args = [], options = {}) {
  const powershell = findPowerShell();
  const commandArgs = [
    "-NoProfile",
    "-ExecutionPolicy",
    "Bypass",
    "-File",
    scriptPath,
    ...args
  ];

  return new Promise((resolve, reject) => {
    const child = spawn(powershell, commandArgs, {
      cwd: options.cwd,
      stdio: "inherit"
    });

    child.on("error", reject);
    child.on("exit", (code) => {
      if (code === 0) {
        resolve();
        return;
      }

      const error = new Error(`PowerShell script failed with exit code ${code}: ${scriptPath}`);
      error.exitCode = code || 1;
      reject(error);
    });
  });
}
