import { NextResponse } from "next/server";
import { withAuth, NextRequestWithAuth } from "next-auth/middleware";
import getConfig from "next/config";

const rewriteURL = (request: NextRequestWithAuth, originBaseURL: string, destinationBaseURL: string, headers: any = {}) => {
  if (request.nextUrl.protocol.startsWith('ws')) {
    return NextResponse.next();
  }

  if (request.nextUrl.pathname.includes('/_next/static/development/')) {
    return NextResponse.next();
  }

  const destinationURL = request.url.replace(originBaseURL, destinationBaseURL);
  console.log(`Rewriting ${request.url} to ${destinationURL}`);

  const requestHeaders = new Headers(request.headers);
  for (const [key, value] of Object.entries(headers)) {
    // @ts-ignore
    requestHeaders.set(key, value);
  }
  requestHeaders.delete('connection');

  // console.log({ finalHeaders: requestHeaders });

  return NextResponse.rewrite(new URL(destinationURL), { request: { headers: requestHeaders } });
};

const checkRewrites = async (request: NextRequestWithAuth) => {
  console.log({ currentURL: request.nextUrl.href });

  const leafcutterBaseURL = process.env.LEAFCUTTER_URL ?? "http://localhost:3000";
  const opensearchDashboardsURL = process.env.OPENSEARCH_URL ?? "http://localhost:5602";

  if (request.nextUrl.pathname.startsWith('/proxy/opensearch')) {
    console.log('proxying to zammad');
    const { token } = request.nextauth;
    const auth = `${token?.email?.toLowerCase()}:${process.env.OPENSEARCH_USER_PASSWORD}`;
    const buff = Buffer.from(auth);
    const base64data = buff.toString("base64");
    const headers = {
      'X-Proxy-User': token?.email?.toLowerCase(),
      "X-Proxy-Roles": "leafcutter_user",
      "Authorization": `Basic ${base64data}`
    };

    console.log({ headers });

    return rewriteURL(request, `${leafcutterBaseURL}/proxy/opensearch`, opensearchDashboardsURL, headers);
  }
};

export default withAuth(
  checkRewrites,
  {
    pages: {
      signIn: `/login`,
    },
    callbacks: {
      authorized: ({ token, req }) => {
        const {
          url,
          headers,
        } = req;

        // check login page
        const parsedURL = new URL(url);
        if (parsedURL.pathname.startsWith('/login')) {
          return true;
        }

        // check session auth
        const authorizedDomains = ["redaranj.com", "digiresilience.org"];
        const userDomain = token?.email?.toLowerCase().split("@").pop() ?? "unauthorized.net";

        if (authorizedDomains.includes(userDomain)) {
          return true;
        }

        return false;
      },
    }
  }
);
