/**
 * Route Guard Component
 * 路由守卫组件 - 处理认证和授权
 */

import { Navigate } from "react-router-dom";
import type { ReactNode } from "react";
import type { User } from "../providers/AuthContext";

interface RouteGuardProps {
  isAuthenticated: boolean;
  isAllowed?: boolean;
  redirectTo?: string;
  children: ReactNode;
}

/**
 * Protected route wrapper
 * Redirects to auth page if not authenticated
 */
export const ProtectedRoute = ({ 
  isAuthenticated,
  isAllowed = true,
  redirectTo = "/", 
  children 
}: RouteGuardProps) => {
  if (!isAuthenticated) {
    return <Navigate to={redirectTo} replace />;
  }

  return isAllowed ? <>{children}</> : <Navigate to="/forbidden" replace />;
};

/**
 * Public route wrapper
 * Redirects to home if already authenticated
 */
export const PublicRoute = ({ 
  isAuthenticated, 
  redirectTo = "/home", 
  children 
}: RouteGuardProps) => {
  return !isAuthenticated ? <>{children}</> : <Navigate to={redirectTo} replace />;
};

export const canUseRoute = (user: User | null, predicate?: (user: User) => boolean): boolean =>
  !predicate || (user ? predicate(user) : false);

