const http = require("http");
const https = require("https");

function request(url, timeoutMs) {
  return new Promise((resolve, reject) => {
    const client = url.startsWith("https:") ? https : http;
    const req = client.get(url, { timeout: timeoutMs }, (res) => {
      res.resume();
      resolve({
        statusCode: res.statusCode,
        ok: res.statusCode >= 200 && res.statusCode < 300,
      });
    });

    req.on("timeout", () => {
      req.destroy(new Error(`Health check timed out after ${timeoutMs}ms`));
    });
    req.on("error", reject);
  });
}

async function checkHttpHealth(config) {
  try {
    const result = await request(config.healthUrl, config.healthTimeoutMs);
    if (!result.ok) {
      return {
        ok: false,
        type: "critical",
        code: "smartcoin_health_bad_status",
        message: `SmartCoin health URL returned HTTP ${result.statusCode}.`,
        details: {
          url: config.healthUrl,
          statusCode: result.statusCode,
        },
      };
    }

    return {
      ok: true,
      code: "smartcoin_health_ok",
      details: {
        url: config.healthUrl,
        statusCode: result.statusCode,
      },
    };
  } catch (error) {
    return {
      ok: false,
      type: "critical",
      code: "smartcoin_health_failed",
      message: `SmartCoin health check failed: ${error.message}`,
      details: {
        url: config.healthUrl,
        error: error.message,
      },
    };
  }
}

module.exports = {
  checkHttpHealth,
};
