const http = require("http");

function dockerRequest(path) {
  return new Promise((resolve, reject) => {
    const options = {
      socketPath: "/var/run/docker.sock",
      path,
      method: "GET"
    };

    const req = http.request(options, (res) => {
      let data = "";
      res.on("data", chunk => data += chunk);
      res.on("end", () => {
        try {
          resolve(JSON.parse(data));
        } catch {
          resolve(data);
        }
      });
    });

    req.on("error", reject);
    req.end();
  });
}

async function isContainerRunning(name) {
  try {
    const data = await dockerRequest(`/containers/${name}/json`);
    return data.State?.Running === true;
  } catch {
    return false;
  }
}

async function networkContainsContainer(networkName, containerName) {
  try {
    const data = await dockerRequest(`/networks/${networkName}`);
    if (!data.Containers) return false;
    return Object.values(data.Containers)
      .some(c => c.Name === containerName);
  } catch {
    return false;
  }
}

module.exports = { isContainerRunning, networkContainsContainer };
