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

const rewriteURL = (
  request: NextRequestWithAuth,
  originBaseURL: string,
  destinationBaseURL: string,
  headers: any = {},
) => {
  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)) {
    requestHeaders.set(key, value as string);
  }
  requestHeaders.delete("connection");

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

const checkRewrites = async (request: NextRequestWithAuth) => {
  const linkBaseURL = process.env.LINK_URL ?? "http://localhost:3000";
  const zammadURL = process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080";
  const opensearchDashboardsURL =
    process.env.OPENSEARCH_DASHBOARDS_URL ?? "http://macmini:5601";
  const zammadPaths = ["/zammad", "/api/v1", "/auth/sso", "/assets", "/mobile"];
  const { token } = request.nextauth;
  const email = token?.email?.toLowerCase() ?? "unknown";
  let headers = { "x-forwarded-user": email };

  if (request.nextUrl.pathname.startsWith("/dashboards")) {
    const roles: string[] = (token?.roles as string[]) ?? [];
    const leafcutterRole = roles.includes("admin")
      ? "leafcutter_admin"
      : "leafcutter_user";
    headers["x-forwarded-roles"] = "admin"; // leafcutterRole;
    // headers["secruitytenant"] = "global";
    // headers["x-forwarded-for"] = 'link';

    return rewriteURL(
      request,
      `${linkBaseURL}/dashboards`,
      opensearchDashboardsURL,
      headers,
    );
  } else if (request.nextUrl.pathname.startsWith("/zammad")) {
    return rewriteURL(request, `${linkBaseURL}/zammad`, zammadURL, headers);
  } else if (zammadPaths.some((p) => request.nextUrl.pathname.startsWith(p))) {
    return rewriteURL(request, linkBaseURL, zammadURL, headers);
  }

  return NextResponse.next();
};

export default withAuth(checkRewrites, {
  pages: {
    signIn: `/login`,
  },
  callbacks: {
    authorized: ({ token, req }) => {
      console.log({ p: req.nextUrl.pathname });
      if (req.nextUrl.pathname.startsWith("/api/v1/")) {
        return true;
      }

      if (process.env.SETUP_MODE === "true") {
        return true;
      }

      const roles: any = token?.roles ?? [];
      if (roles.includes("admin") || roles.includes("agent")) {
        return true;
      }

      return false;
    },
  },
});

export const config = {
  matcher: [
    "/((?!ws|wss|api/signal|api/whatsapp|api/facebook|_next/static|_next/image|favicon.ico).*)",
  ],
};
