import { createProxyMiddleware } from "http-proxy-middleware";
import { NextApiRequest, NextApiResponse } from "next";
import { getToken } from "next-auth/jwt";

const withAuthInfo =
  (handler: any) => async (req: NextApiRequest, res: NextApiResponse) => {
    const session: any = await getToken({
      req,
      secret: process.env.NEXTAUTH_SECRET,
    });

    if (!session) {
      return res.redirect("/login");
    }

    req.headers["x-proxy-user"] = session.email.toLowerCase();
    req.headers["x-proxy-roles"] = "leafcutter_user";
    const auth = `${session.email.toLowerCase()}:${process.env.OPENSEARCH_USER_PASSWORD}`;
    const buff = Buffer.from(auth);
    const base64data = buff.toString("base64");
    req.headers.Authorization = `Basic ${base64data}`;
    return handler(req, res);
  };

const proxy = createProxyMiddleware({
  target: process.env.OPENSEARCH_DASHBOARDS_URL,
  changeOrigin: true,
  xfwd: true,
});

export default withAuthInfo(proxy);

export const config = {
  api: {
    bodyParser: false,
    externalResolver: true,
  },
};
