const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");

const app = express();

const TARGET = "http://localhost:9010";

app.use(
  "/",
  createProxyMiddleware({
    target: TARGET,
    changeOrigin: true,
    ws: true,
    xfwd: true,
    secure: false,

    onProxyReq: (proxyReq, req) => {
      proxyReq.setHeader("X-Real-IP", req.ip);
      proxyReq.setHeader("X-Forwarded-Host", req.headers.host || "");
      proxyReq.setHeader("X-Forwarded-Proto", req.protocol);
    },

    onError: (err, req, res) => {
      console.error("Proxy error:", err.message);
      res.status(502).send("Bad Gateway: proxy target error");
    }
  })
);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Node reverse proxy running on port ${PORT}`);
  console.log(`Proxy target: ${TARGET}`);
});