import { getToken, JWT } from "next-auth/jwt";
import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { excludedPaths, protectedPath } from "../server/config";
import { getLocale, locales } from "./lib/locales";

export async function middleware(request: NextRequest & { token: JWT }) {
  const { pathname } = request.nextUrl;

  if (pathname === "/") {
    return NextResponse.redirect(`/auth/login`);
  }

  if (excludedPaths.some((path) => pathname.startsWith(path))) return;

  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
  );

  if (!pathnameHasLocale) {
    const cookiesStore = await cookies();
    const savedLocale = cookiesStore.get("LOCALE");

    const locale = savedLocale?.value || getLocale();

    request.nextUrl.pathname = `/${locale}${pathname}`;

    return NextResponse.redirect(request.nextUrl);
  }

  const locale = pathname.slice(0, 3);

  if (protectedPath.includes(pathname.slice(3))) {
    const token = await getToken({
      req: request,
      secret: process.env.JWT_SECRET,
    });

    const url = process.env.NEXT_PUBLIC_URL;

    if (!token) {
      return NextResponse.redirect(`${url}${locale}/auth/login`);
    }

    request.token = token;
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    {
      source: "/((?!_next).*)",
    },
  ],
};
