import { NextRequest, NextResponse } from "next/server"
import { getCookieCache } from "better-auth/cookies"

const PUBLIC_PATHS = [/^\/login$/, /^\/api\/auth/, /^\/_next\//, /^\/favicon/]
const ADMIN_ONLY_PATHS = [/^\/admin(?:$|\/)/]
const PORTAL_HOME = "/portal"
const APP_HOME = "/dashboard"

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

  if (PUBLIC_PATHS.some((pattern) => pattern.test(pathname))) {
    return NextResponse.next()
  }

  const session = await getCookieCache(request)

  if (!session?.user) {
    const redirectUrl = new URL("/login", request.url)
    redirectUrl.searchParams.set("callbackUrl", pathname + search)
    return NextResponse.redirect(redirectUrl)
  }

  const role = (session.user as { role?: string })?.role?.toLowerCase() ?? "agent"

  const isAdmin = role === "admin"
  if (!isAdmin && ADMIN_ONLY_PATHS.some((pattern) => pattern.test(pathname))) {
    return NextResponse.redirect(new URL(APP_HOME, request.url))
  }

  return NextResponse.next()
}

export const config = {
  runtime: "nodejs",
  matcher: ["/(.*)"],
}
