import { NextRequest, NextResponse } from "next/server";
import { decrypt } from "@/lib/session";
import { cookies } from "next/headers";

// Define all public routes here
const publicRoutes = ["/login"];

export default async function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;
  const isPublicRoute = publicRoutes.includes(path);

  // Get the session cookie and decrypt it
  const cookie = (await cookies()).get("session")?.value;
  const session = await decrypt(cookie);

  // If a user is NOT authenticated and is trying to access a PROTECTED route,
  // redirect them to the login page.
  if (!session?.user && !isPublicRoute) {
    return NextResponse.redirect(new URL("/login", req.nextUrl));
  }

  // If a user IS authenticated and is trying to access a PUBLIC route (like /login),
  // redirect them to a protected route (e.g., a dashboard or home page).
  if (session?.user && isPublicRoute) {
    return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
  }

  if (session?.user && path == "/") {
    return NextResponse.redirect(new URL("/dashboard", req.nextUrl));
  }

  // Otherwise, allow the request to proceed
  return NextResponse.next();
}

// Routes Middleware should not run on
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
};
