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

export default async function middleware(req: NextRequest) {
  const { pathname, origin, search } = req.nextUrl

  // Skip auth check for certain paths
  const ignorePaths = [
    "/api/auth",
    "/_next",
    "/favicon.ico",
    "/manifest.json",
    "/login",
    "/onboarding",
  ]
  if (ignorePaths.some(p => pathname.startsWith(p))) {
    return NextResponse.next()
  }

  const res = NextResponse.next()
  const session = await getSession(req, res)

  // Handle unauthenticated user
  if (!session?.user) {
    if (pathname.startsWith("/api/") || pathname === "/api") {
      // Return JSON error for actual API routes (must have /api/ or be exactly /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(`/login?returnTo=${returnTo}`, origin)
    return NextResponse.redirect(loginUrl)
  }

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

  return res
}

export const config = {
  matcher: [
    "/",
    "/app/:path*",
    "/trace/:path*",
    "/billing",
    "/billing/:path*",
    "/apikeys",
    "/apikeys/:path*",
    "/repositories",
    "/repositories/:path*",
    "/review-optimizations",
    "/review-optimizations/:path*",
    "/getting-started",
    "/getting-started/:path*",
    "/dashboard",
    "/dashboard/:path*",
    "/observability",
    "/observability/:path*",
    "/members",
    "/members/:path*",
    "/subscribe/:path*",
  ],
}
