const { fetchWhois } = require("../whois");

// Feature 27: WHOIS endpoint
async function handleWhoisRoute(req, res, url) {
    const resource = url.searchParams.get("resource") || "";
    if (!resource) {
      res.writeHead(400);
      return res.end(JSON.stringify({ error: "Missing resource parameter (ASN, prefix, or domain)" }));
    }
    const start = Date.now();
    try {
      const whoisResult = await fetchWhois(resource);
      if (!whoisResult || typeof whoisResult !== "object") {
        res.writeHead(503);
        return res.end(JSON.stringify({ error: "WHOIS data temporarily unavailable" }));
      }
      whoisResult.meta = { duration_ms: Date.now() - start, timestamp: new Date().toISOString() };
      return res.end(JSON.stringify(whoisResult, null, 2));
    } catch (err) {
      res.writeHead(500);
      return res.end(JSON.stringify({ error: "WHOIS lookup failed", message: err.message }));
    }

}

module.exports = { handleWhoisRoute };
