import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { buildLoginRedirectPath } from "@/features/auth/loginRedirect.js";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import { defaultAdminPath } from "./routeConfig";

export function RequireAuth() {
  const { loading, user } = useAuth();
  const location = useLocation();

  if (loading) {
    return <PageSkeleton />;
  }

  if (!user) {
    return <Navigate to={buildLoginRedirectPath(location)} state={{ from: location }} replace />;
  }

  return <Outlet />;
}

export function RequirePermission({ children, code }) {
  const { can } = useAuth();

  if (!can(code)) {
    return <Navigate to={defaultAdminPath} replace />;
  }

  return children;
}

export function RequireAppScope({ children }) {
  const { hasAppAccess, loading } = useAppScope();

  if (loading) {
    return <PageSkeleton />;
  }
  if (!hasAppAccess) {
    return <Navigate to={defaultAdminPath} replace />;
  }
  return children;
}
