import { NextResponse } from "next/server";
import { headers } from "next/headers";
import { getToken } from "next-auth/jwt";

import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";

const locales = ["en", "de"];

function getLocale(request, current) {
  /*
   * If the user has a locale in its referer, keep it.
   */
  if (current) return current;

  /*
   * Read the accept-language header and match it to a provided locale
   */
  const headers = {
    "accept-language": request.headers.get("accept-language"),
  };
  let languages = new Negotiator({ headers }).languages();
  let defaultLocale = "en";

  let lang = match(languages, locales, defaultLocale);

  return lang;
}

export async function middleware(request) {
  const token = await getToken({ req: request });
  const { pathname, search } = request.nextUrl;
  const current = headers().get("next-url");
  const callback = decodeURIComponent(request.nextUrl.search).split("=")[1];

  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
  );

  const refererHasLocale = locales.some(
    (locale) =>
      current &&
      (current.startsWith(`/${locale}/`) || current === `/${locale}`),
  );

  const locale = pathnameHasLocale
    ? pathname.substr(1, 2)
    : refererHasLocale
      ? getLocale(request, current.substr(1, 2))
      : getLocale(request, "");

  let forward = pathname;

  if (!pathnameHasLocale) {
    request.nextUrl.pathname = `/${locale}${pathname}`;
    return Response.redirect(request.nextUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!api|static|.*\\..*|_next|favicon.ico|robots.txt).*)"],
};