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

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 linkBaseURL = process.env.LINK_URL ?? "http://localhost:3000";
  const zammadURL = process.env.ZAMMAD_URL ?? "http://zammad-nginx:8080";
  const leafcutterURL = process.env.LEAFCUTTER_URL ?? "https://lc.digiresilience.org";
  const metamigoURL = process.env.METAMIGO_URL ?? "http://metamigo-frontend:3000";

  console.log({ linkBaseURL, zammadURL, leafcutterURL, metamigoURL });

  if (request.nextUrl.pathname.startsWith('/proxy/leafcutter')) {
    const headers = { 'X-Leafcutter-Embedded': "true" };
    return rewriteURL(request, linkBaseURL, leafcutterURL, headers);
  } else if (request.nextUrl.pathname.startsWith('/proxy/metamigo')) {
    return rewriteURL(request, linkBaseURL, metamigoURL);
  } else if (request.nextUrl.pathname.startsWith('/proxy/zammad')) {
    console.log('proxying to zammad');
    const { token } = request.nextauth;

    // console.log({ nextauth: request.nextauth });

    const headers = {
      'X-Forwarded-User': token.email.toLowerCase(),
      host: 'link-stack-dev.digiresilience.org'
    };

    // console.log({ headers });

    return rewriteURL(request, `${linkBaseURL}/proxy/zammad`, zammadURL, headers);
  } else if (request.nextUrl.pathname.startsWith('/assets') || request.nextUrl.pathname.startsWith('/api/v1')) {
    console.log('asset');
    return rewriteURL(request, linkBaseURL, zammadURL);
  } else if (request.nextUrl.pathname.startsWith('/proxy/assets')) {
    console.log('proxy asset');
    return rewriteURL(request, `${linkBaseURL}/proxy`, zammadURL);
  } else if (request.nextUrl.pathname.startsWith('/proxy/api')) {
    console.log('proxy api');
    return rewriteURL(request, `${linkBaseURL}/proxy`, zammadURL);
  }
};

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;
      },
    }
  }
);
