import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const token = request.cookies.get("auth_token")?.value;
  const { pathname } = request.nextUrl;

  // If the user is trying to access the login page
  if (pathname === "/login") {
    if (token) {
      // If already logged in, redirect them to the dashboard
      const dashboardUrl = request.nextUrl.clone();
      dashboardUrl.pathname = "/dashboard";
      return NextResponse.redirect(dashboardUrl);
    }
    // If not logged in, allow them to view the login page
    return NextResponse.next();
  }

  // For protected routes, redirect to login if no token is present
  if (!token) {
    const loginUrl = request.nextUrl.clone();
    loginUrl.pathname = "/login";
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  // Run middleware on these routes, including /login
  matcher: [
    "/login",
    "/dashboard/:path*",
    "/meetings/:path*",
    "/settings/:path*",
    "/profile/:path*",
    "/upload/:path*",
    "/onboarding",
    "/admin/:path*",
    "/pending-approval",
    "/denied",
  ],
};
