import { NextRequest, NextResponse } from "next/server";
import { publicRoutes } from "@/src/constants/middleware";
import { verifyJWT } from "@/src/lib/jwt";
import { auth } from "@/auth";

export default async function middleware(request: NextRequest) {
  try {
    const pathname = request.nextUrl.pathname;
    console.log("Middleware executing for path:", pathname);
    //for bypass the middleware for routes
    // if (pathname) return NextResponse.next();
    if (publicRoutes(pathname)) {
      console.log("Path is public, continuing...");
      return NextResponse.next();
    }
    const authResult = await auth(request);
    if (authResult) return authResult;

    const token = request.headers.get("authorization")?.split(" ")[1] || "";
    console.log("Token extracted:", token);

    if (!token) {
      console.log("No token found, throwing 403 error...");
      return new NextResponse(null, { status: 403 });
    }

    const decodedToken = verifyJWT(token);
    if (!decodedToken) {
      console.log("Invalid token, throwing 403 error...");
      return new NextResponse(null, { status: 403 });
    }

    console.log("Token verified, allowing access to protected route");
    return NextResponse.next();
  } catch (error) {
    console.error("Error in middleware:", error);
    return new NextResponse(null, { status: 500 });
  }
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * - assets in the public folder
     */
    "/((?!api|_next/static|_next/image|favicon.ico|public|manifest.json).*)",
  ],
};
S2769: No overload matches this call.
Overload 1 of 4,
(args_0: GetServerSidePropsContext): Promise<Session | null>
, gave the following error.
Argument of type NextRequest is not assignable to parameter of type GetServerSidePropsContext
Type NextRequest is missing the following properties from type GetServerSidePropsContext: req, res, query, resolvedUrl
Overload 2 of 4,
(args_0: (req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>): AppRouteHandlerFn
, gave the following error.
Argument of type NextRequest is not assignable to parameter of type
(req: NextAuthRequest, ctx: AppRouteHandlerFnContext) => void | Response | Promise<void | Response>
Type NextRequest provides no match for the signature
(req: NextAuthRequest, ctx: AppRouteHandlerFnContext): void | Response | Promise<void | Response>
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
// Your own logic for dealing with plaintext password strings; be careful!
import { saltAndHashPassword } from "@/utils/password";

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Credentials({
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      credentials: {
        email: {},
        password: {},
      },
      authorize: async (credentials) => {
        let user = null;

        // logic to salt and hash password
        const pwHash = saltAndHashPassword(credentials.password);

        // logic to verify if the user exists
        user = await getUserFromDb(credentials.email, pwHash);

        if (!user) {
          // No user found, so this is their first attempt to login
          // meaning this is also the place you could do registration
          throw new Error("User not found.");
        }

        // return user object with their profile data
        return user;
      },
    }),
  ],
});