const http = require("http");

// Several routes were extracted into src/api/ + src/features/*/routes.ts
// (Fastify, dist/api/index.js, run as a separate PM2 process on
// API_SERVER_PORT) but were never re-wired here after that migration —
// they just silently 404'd. This forwards those specific paths through
// rather than reimplementing them inline a second time.
const API_SERVER_PORT = parseInt(process.env.API_SERVER_PORT || "3102", 10);

function proxyToApiServer(req, res, targetUrl) {
  const proxyReq = http.request(
    {
      hostname: "127.0.0.1",
      port: API_SERVER_PORT,
      path: targetUrl,
      method: req.method,
      headers: Object.assign({}, req.headers, { host: "127.0.0.1:" + API_SERVER_PORT }),
    },
    (proxyRes) => {
      res.writeHead(proxyRes.statusCode, proxyRes.headers);
      proxyRes.pipe(res);
    }
  );
  proxyReq.on("error", (err) => {
    console.error("[API Proxy] Error forwarding " + targetUrl + ":", err.message);
    if (!res.headersSent) {
      res.writeHead(502, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ error: "API server unavailable", detail: err.message }));
    }
  });
  req.pipe(proxyReq);
}

module.exports = { proxyToApiServer, API_SERVER_PORT };
