/* eslint-disable react-hooks/exhaustive-deps */ import { useRouter } from "next/navigation"; import { useEffect } from "react"; import { useIsMounted } from "usehooks-ts"; import type { ProviderProps } from "@/@types/types/provider-props.types"; import { useAuth } from "@/features/auth/hooks/use-auth"; import { usePageInfo } from "@/hooks/use-page-info"; import { cookieHelper } from "@/libs/helpers/cookie-helper"; import { CheckProfileAndRedirect } from "@/libs/helpers/profile-helper"; import { useProfileInformationQuery } from "@/services/eva-display/profile/profile-information.services"; import { usePermissionMution } from "@/services/eva-permission/permission.services"; import { NETWORK_ERROR_THRESHOLD, useInterceptorStore, } from "@/store/interceptor-store/use-interceptor-store"; const AuthProvider = (props: ProviderProps) => { const isMounted = useIsMounted(); const { setUser, isAuthenticated } = useAuth(); const mutatePermission = usePermissionMution(); const { networkError } = useInterceptorStore(); const { info } = usePageInfo(); const router = useRouter(); useProfileInformationQuery({ onSuccess: (data) => { if (data) { if (info?.queryParams.check?.includes("information")) { if (!CheckProfileAndRedirect(data)) return; router.push(info.path); } // This control for the user to be redirected to the profile page if the user's profile is not complete. mutatePermission.mutateAsync().then((res) => { if (res.success) { setUser({ id: data.result.id, email: data.result.email, userGuidId: data.result.userGuidId, fullname: `${data.result.userDetail.firstName} ${data.result.userDetail.lastName}`, permissions: res.permissions, }); } }); } }, }); function logout() { cookieHelper.delete("client-token"); cookieHelper.delete("auth"); window.location.reload(); } useEffect(() => { if (networkError.count >= NETWORK_ERROR_THRESHOLD) { networkError.reset(); logout(); } }, [networkError.count]); useEffect(() => { if (isMounted()) { if (isAuthenticated) { if (info?.path === "/auth") { router.push("/"); } } } }, [info, isAuthenticated]); return props.children; }; export default AuthProvider;