import { cookies } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { getUserData } from "./lib/session";
import { cache } from "react";

const validateAuthentication = cache(async (token: undefined | string) => {
  "use server";
  if (!token) return false;

  try {
    const userData = await getUserData(token);
    return !!userData;
  } catch (error: unknown) {
    (await cookies()).delete("accessToken");
    console.log(error);
    return false;
  }
});

export default async function middleware(req: NextRequest) {
  try {

    const requestHeaders = new Headers(req.headers);
    requestHeaders.set("x-pathname", req.nextUrl.pathname);

    const nextAuthSid = (await cookies()).get("accessToken")?.value;
    const isAuthenticated = await validateAuthentication(nextAuthSid);

    const isAuthRoute = req.nextUrl.pathname.startsWith("/auth");
    const isMemberRoute = req.nextUrl.pathname.startsWith("/member");


    if (isAuthenticated && isAuthRoute) {
      // If user is already authenticated, prevent access to /auth/* and redirect to /member/dashboard
      console.log("User is authenticated, redirecting to /member/dashboard");
      return NextResponse.redirect(new URL("/member/dashboard", req.url));
    }

    if (!isAuthenticated && isMemberRoute) {
      // If user is not authenticated, prevent access to /member/* and redirect to /auth/login
      console.log("User is not authenticated, redirecting to /auth/login");
      return NextResponse.redirect(new URL("/auth/login", req.url));
    }

    return NextResponse.next({
      request: {
        headers: requestHeaders,
      },
    });
  } catch (error) {
    console.log("Middleware error:", error);
    return NextResponse.next();
  }
}

export const config = {
  matcher: ["/auth/:path*", "/member/:path*"],
};
