import { Express, Response } from "express";
import { createProxyMiddleware } from "http-proxy-middleware";

const METASET_HOST = process.env.METASET_HOST || "metaset";
const METASET_PORT = parseInt(process.env.METASET_PORT || "8100", 10);
const METASET_TIMEOUT = 60000;

export function setupMetasetProxy(app: Express): void {
  const target = `http://${METASET_HOST}:${METASET_PORT}`;

  const metasetProxy = createProxyMiddleware({
    target,
    changeOrigin: true,
    timeout: METASET_TIMEOUT,
    proxyTimeout: METASET_TIMEOUT,
    pathRewrite: { "^/metaset": "" },
    on: {
      error: (err, _req, res) => {
        console.error("[Metaset Proxy] Error:", err.message);
        if (res && typeof (res as Response).status === "function") {
          (res as Response).status(502).json({
            error: "Metaset indisponível",
            message: "O Metaset BI está iniciando. Tente novamente em alguns segundos.",
            target,
          });
        }
      },
      proxyRes: (proxyRes) => {
        const location = proxyRes.headers["location"];
        if (location && typeof location === "string" && location.startsWith("/")) {
          proxyRes.headers["location"] = `/metaset${location}`;
        }
      },
    },
  });

  app.use("/metaset", metasetProxy);
  console.log(`[Metaset Proxy] Configurado -> /metaset/* => ${target}`);
}
