import { NextResponse } from "next/server"

import { auth } from "@/lib/auth"

export default auth((req) => {
  const { nextUrl } = req
  const isAuthenticated = !!req.auth

  // Public routes that don't require authentication
  const publicRoutes = [
    "/login",
    "/register",
    "/forgot-password",
    "/api/auth",
    "/portal-login",
  ]
  const isPublicRoute = publicRoutes.some((route) =>
    nextUrl.pathname.startsWith(route)
  )

  // Portal routes — allow without admin auth (mock for now)
  const isPortalRoute = nextUrl.pathname.startsWith("/portal")

  if (isPublicRoute || isPortalRoute) {
    // If user is already authenticated and tries to access login, redirect based on role
    if (isAuthenticated && nextUrl.pathname.startsWith("/login")) {
      const role = req.auth?.user?.role
      const redirectPath = getRedirectForRole(role)
      return NextResponse.redirect(new URL(redirectPath, nextUrl))
    }
    return NextResponse.next()
  }

  // Redirect unauthenticated users to login
  if (!isAuthenticated) {
    const loginUrl = new URL("/login", nextUrl)
    loginUrl.searchParams.set("callbackUrl", nextUrl.pathname)
    return NextResponse.redirect(loginUrl)
  }

  return NextResponse.next()
})

function getRedirectForRole(role: string | undefined): string {
  switch (role) {
    case "ADMIN":
    case "STAFF":
    case "PREVENTION_OFFICER":
      return "/dashboard"
    case "MEMBER":
      return "/portal/dashboard"
    default:
      return "/dashboard"
  }
}

export const config = {
  matcher: [
    // Protect all routes EXCEPT:
    // - /login, /register, /forgot-password (auth pages)
    // - /portal-login (portal auth page)
    // - /api/auth (NextAuth API routes)
    // - /_next/static, /_next/image (Next.js internals)
    // - /favicon.ico, /images (public assets)
    "/((?!login|register|forgot-password|portal-login|api/auth|_next/static|_next/image|favicon.ico|images).*)",
  ],
}
