import { useIdentityAuthSession } from "@erp/identity/client";
import { LoadingOverlay } from "@repo/rdx-ui/components";
import type { ReactNode } from "react";
import { Navigate, useSearchParams } from "react-router-dom";

interface PublicOnlyRouteProps {
  children: ReactNode;
}

export const PublicOnlyRouteGuard = ({ children }: PublicOnlyRouteProps) => {
  const { getAuthenticatedRedirectPath, isAuthenticated, isLoading } = useIdentityAuthSession();
  const [searchParams] = useSearchParams();

  const returnTo = searchParams.get("returnTo");

  if (isLoading) {
    return <LoadingOverlay />;
  }

  if (isAuthenticated) {
    return (
      <Navigate
        replace
        to={getAuthenticatedRedirectPath({
          returnTo,
        })}
      />
    );
  }

  return <>{children}</>;
};
