import type { ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuthStore } from '@/stores/authStore'

export interface ProtectedRouteProps {
  children: ReactNode
  /** OR semantics — user's role must be in this list (at least one match). */
  requiredRoles?: string[]
  /** OR semantics — user must have at least one of these permission codes. */
  requiredPermissions?: string[]
}

/**
 * Wraps a route with authentication and optional authorization guards.
 *
 * Guard order:
 * 1. No user → redirect to /login
 * 2. requiredRoles provided and user.rol not in list → redirect to /
 * 3. requiredPermissions provided and user has none of them → redirect to /
 * 4. All checks pass → render children
 */
export function ProtectedRoute({
  children,
  requiredRoles,
  requiredPermissions,
}: ProtectedRouteProps) {
  const user = useAuthStore((s) => s.user)

  // 1. Authentication check
  if (!user) {
    return <Navigate to="/login" replace />
  }

  // 2. Role check (OR: user.rol must be included in the list)
  if (requiredRoles && requiredRoles.length > 0 && !requiredRoles.includes(user.rol)) {
    return <Navigate to="/" replace />
  }

  // 3. Permission check (OR: user must have at least one of the required codes)
  if (requiredPermissions && requiredPermissions.length > 0) {
    const hasPermission = requiredPermissions.some((p) => user.permisos.includes(p))
    if (!hasPermission) {
      return <Navigate to="/" replace />
    }
  }

  return <>{children}</>
}
