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

/*

  if (validDomains.includes(domain)) {
    res.headers.set("Access-Control-Allow-Origin", origin);
    res.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    res.headers.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  }


  */

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

    const requestSignature = req.query.signature;
    const url = new URL(req.headers.referer as string);
    const referrerSignature = url.searchParams.get("signature");

    console.log({ requestSignature, referrerSignature });
    const isAppPath = !!req.url?.startsWith("/app");
    const isResourcePath = !!req.url?.match(/\/(api|app|bootstrap|3961|ui|translations|internal|login|node_modules)/);

    if (requestSignature && isAppPath) {
      console.log("Has Signature");
    }

    if (referrerSignature && isResourcePath) {
      console.log("Has Signature");
    }

    if (!email) {
      return res.status(401).json({ error: "Not authorized" });
    }

    req.headers["x-proxy-user"] = email;
    req.headers["x-proxy-roles"] = "leafcutter_user";
    const auth = `${email}:${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,
  },
};
