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

const { setPort } = require("./use-api");

module.exports = ({ cwd }) => {
  const serverPath = path.join(__dirname, "test-server.js");

  return new Promise((resolve, reject) => {
    const medusaProcess = spawn("node", [path.resolve(serverPath)], {
      cwd,
      env: {
        ...process.env,
        NODE_ENV: "development",
        JWT_SECRET: "test",
        COOKIE_SECRET: "test",
      },
      stdio: ["ignore", "ignore", "inherit", "ipc"],
    });

    medusaProcess.on("uncaughtException", (err) => {
      medusaProcess.kill();
    });

    medusaProcess.on("message", (port) => {
      setPort(port);
      resolve(medusaProcess);
    });
  });
};
