import { type NextRequest, NextResponse } from "next/server"
import { auth0 } from "@/lib/auth0"
import { isTeamMemberCheck, isMembenchAllowed } from "@/lib/team-members"

export async function proxy(req: NextRequest) {
  // Let Auth0 handle auth routes (/auth/login, /auth/callback, /auth/logout, etc.)
  const authRes = await auth0.middleware(req)

  const { pathname, origin, search } = req.nextUrl

  // For auth routes, return the Auth0 response directly
  if (pathname.startsWith("/auth")) {
    return authRes
  }

  // Skip auth check for public/static paths
  const ignorePaths = [
    "/_next",
    "/favicon.ico",
    "/manifest.json",
    "/login",
    "/onboarding",
    "/api/healthcheck",
    "/codeflash/auth/oauth",
  ]
  if (ignorePaths.some(p => pathname.startsWith(p))) {
    return authRes
  }

  const session = await auth0.getSession(req)

  // Handle unauthenticated user
  if (!session?.user) {
    if (pathname.startsWith("/api/") || pathname === "/api") {
      return NextResponse.json(
        {
          error: "not_authenticated",
          description: "The user does not have an active session or is not authenticated",
        },
        { status: 401 },
      )
    }

    // Redirect to login for page routes with returnTo
    const returnTo = encodeURIComponent(pathname + search)
    const loginUrl = new URL(`/auth/login?returnTo=${returnTo}`, origin)
    return NextResponse.redirect(loginUrl)
  }

  if (
    pathname.startsWith("/observability") ||
    pathname.startsWith("/roadmap") ||
    pathname.startsWith("/report")
  ) {
    if (!isTeamMemberCheck(session.user)) {
      return NextResponse.redirect(new URL("/", origin))
    }
  }

  if (pathname.startsWith("/membench")) {
    if (!isMembenchAllowed(session.user)) {
      return NextResponse.redirect(new URL("/", origin))
    }
  }

  return authRes
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
}
