import { NextRequestWithAuth, withAuth } from "next-auth/middleware";
// import { authOptions } from "@/config/authConfig";
import { authOptions } from "./config/authConfig";
import { NextFetchEvent, NextResponse } from "next/server";
import { PRIVATE_ROUTES } from "./routes";

const LANG_QUERY_PARAM = "lang";

const authMiddleware = withAuth({
  pages: authOptions.pages,
  callbacks: {
    authorized: ({ req, token }) => {
      if (!Boolean(token)) {
        return Boolean(token);
      }

      // example
      // const abilities = token!.abilities as string[]
      // if (req.nextUrl.pathname.endsWith('/user') && 'abilities dont hv view/maintain user') {
      //   return false
      // }
      return true;
    },
  },
});

export default async function middleware(
  req: NextRequestWithAuth,
  event: NextFetchEvent,
) {
  const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  if (langPref) {
    // Redirect to same url without the lang query param + set cookies
    const newUrl = new URL(req.nextUrl);
    newUrl.searchParams.delete(LANG_QUERY_PARAM);
    const response = NextResponse.redirect(newUrl);
    response.cookies.set("i18next", langPref);
    return response;
  }

  // Matcher for using the auth middleware
  return PRIVATE_ROUTES.some((route) => req.nextUrl.pathname.startsWith(route))
    ? await authMiddleware(req, event) // Let auth middleware handle response
    : NextResponse.next(); // Return normal response
}
