const http = require("http");
const { HTTP_TIMEOUT_GET, HTTP_TIMEOUT_POST } = require("./constants");

function parseBody(raw) {
  try {
    return JSON.parse(raw);
  } catch {
    return raw;
  }
}

function httpGet(url) {
  return new Promise(resolve => {
    const req = http.get(url, res => {
      let body = "";
      res.on("data", chunk => (body += chunk));
      res.on("end", () => resolve({ ok: true, status: res.statusCode, body: parseBody(body) }));
    });
    req.on("error", err => resolve({ ok: false, error: err.message }));
    req.setTimeout(HTTP_TIMEOUT_GET, () => {
      req.destroy();
      resolve({ ok: false, error: "请求超时" });
    });
  });
}

function httpPost(url, data) {
  return new Promise(resolve => {
    const postData = JSON.stringify(data);
    const urlObj = new URL(url);
    const options = {
      hostname: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname,
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(postData)
      }
    };
    const req = http.request(options, res => {
      let body = "";
      res.on("data", chunk => (body += chunk));
      res.on("end", () => {
        try {
          resolve({ ok: true, body: JSON.parse(body) });
        } catch {
          resolve({ ok: false, error: "Invalid JSON response" });
        }
      });
    });
    req.on("error", err => resolve({ ok: false, error: err.message }));
    req.setTimeout(HTTP_TIMEOUT_POST, () => {
      req.destroy();
      resolve({ ok: false, error: "请求超时" });
    });
    req.write(postData);
    req.end();
  });
}

module.exports = { httpGet, httpPost };
