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

const CHECKS_DIR = path.join(__dirname, "checks");

async function runCheck(check) {
  const start = Date.now();

  if (check.type === "docker_container") {
    const result = await dockerApi.isContainerRunning(check.target);
    return {
      status: result ? "OK" : "FAIL",
      message: `Container ${check.target} running: ${result}`,
      duration: Date.now() - start
    };
  }

  if (check.type === "docker_network") {
    const [network, container] = check.target.split(",");
    const result = await dockerApi.networkContainsContainer(network, container);
    return {
      status: result ? "OK" : "FAIL",
      message: `Container ${container} in network ${network}: ${result}`,
      duration: Date.now() - start
    };
  }

  if (check.type === "script") {

    if (!check.script_name) {
      return {
        status: "FAIL",
        message: "No script_name defined",
        duration: Date.now() - start
      };
    }

    return new Promise((resolve) => {
      const scriptPath = path.join(CHECKS_DIR, check.script_name);

      const child = spawn("sh", [scriptPath], {
        timeout: (check.timeout_seconds || 10) * 1000
      });

      child.on("close", (code) => {
        resolve({
          status: code === 0 ? "OK" : "FAIL",
          message: `Exit code: ${code}`,
          duration: Date.now() - start
        });
      });
    });
  }
}

module.exports = runCheck;
