import { NextRequestWithAuth, withAuth } from "next-auth/middleware";
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 }) => {
      const currentTime = Math.floor(Date.now() / 1000);
      
      // Redirect to login if:
      // 1. No token exists
      // 2. Token has an expiry field (exp) and current time has passed it
      if (!token || (token.exp && currentTime > (token.exp as number))) {
        return false; 
      }
      return true;
    },
  },
});

export default async function middleware(
  req: NextRequestWithAuth,
  event: NextFetchEvent,
) {
  // Handle language parameters
  const langPref = req.nextUrl.searchParams.get(LANG_QUERY_PARAM);
  if (langPref) {
    const newUrl = new URL(req.nextUrl);
    newUrl.searchParams.delete(LANG_QUERY_PARAM);
    const response = NextResponse.redirect(newUrl);
    response.cookies.set("i18next", langPref);
    return response;
  }

  // Check if the current URL starts with any string in PRIVATE_ROUTES
  const isPrivateRoute = PRIVATE_ROUTES.some((route) => 
    req.nextUrl.pathname.startsWith(route)
  );

  // Debugging: View terminal logs to see if the path is being caught
  if (req.nextUrl.pathname.startsWith("/ps") || req.nextUrl.pathname.startsWith("/testing")) {
      console.log("--- Middleware Check ---");
      console.log("Path:", req.nextUrl.pathname);
      console.log("Is Private Match:", isPrivateRoute);
  }

  return isPrivateRoute
    ? await authMiddleware(req, event) // Run authentication check
    : NextResponse.next();            // Allow public access
}