import { AuthFailedReplacePath } from "@/constant";
import { useLocation, useNavigate } from "react-router-dom";
import { pathToRegexp } from "path-to-regexp";
import { useDomain } from "@/hook/useDomain";

interface RouteGuardProps {
  children?: React.ReactNode;
  ignorePaths: string[];
}

export const RouteGuard = (props: RouteGuardProps) => {
  const { children, ignorePaths } = props;
  const { userDomainService } = useDomain();
  const { user } = userDomainService;
  const location = useLocation();
  const navigate = useNavigate();

  const ignore = ignorePaths.some((p) =>
    pathToRegexp(p).test(location.pathname)
  );

  if (!ignore && !user.isLoggedIn) {
    userDomainService.userAuth().then(({ success }) => {
      if (!success) navigate(AuthFailedReplacePath);
    });
  }

  return children;
};
