import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { ROUTE_PERMISSIONS } from './lib/rbac'
import { canAccessDbEditor, normalizeRoleForAccess } from './lib/role-access'

// Routes that require authentication
const protectedRoutes = ['/registrations', '/payment', '/profile', '/cashflow', '/analytics', '/admin-panel', '/db-editor']

// Routes that should redirect to home if already authenticated
const guestOnlyRoutes = ['/login']

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value
  const userRole = request.cookies.get('userRole')?.value
  const pathname = request.nextUrl.pathname

  // Check if the current route is protected
  const isProtectedRoute = protectedRoutes.some(route => pathname.startsWith(route))
  const isGuestOnlyRoute = guestOnlyRoutes.some(route => pathname.startsWith(route))

  // Redirect to login if accessing protected route without token
  if (isProtectedRoute && !token) {
    const loginUrl = new URL('/login', request.url)
    loginUrl.searchParams.set('redirect', pathname)
    return NextResponse.redirect(loginUrl)
  }

  // Redirect to home if accessing guest-only route with token
  if (isGuestOnlyRoute && token) {
    return NextResponse.redirect(new URL('/', request.url))
  }

  // Role-based access control
  if (token && userRole) {
    if (pathname.startsWith('/db-editor') && !canAccessDbEditor(userRole)) {
      return NextResponse.redirect(new URL('/', request.url))
    }

    if (pathname.startsWith('/db-editor')) {
      return NextResponse.next()
    }

    const normalizedRole = normalizeRoleForAccess(userRole)
    const allowedRoles = ROUTE_PERMISSIONS[pathname]
    
    // If allowedRoles is defined and has items, check if user's role is allowed
    // If allowedRoles is undefined or empty array, allow access
    if (allowedRoles && allowedRoles.length > 0 && !normalizedRole) {
      return NextResponse.redirect(new URL('/', request.url))
    }

    if (allowedRoles && allowedRoles.length > 0 && normalizedRole && !allowedRoles.includes(normalizedRole)) {
      // User doesn't have permission for this route
      return NextResponse.redirect(new URL('/', request.url))
    }
  }

  return NextResponse.next()
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
}
