import { useIsLoggedIn } from "@/lib/hooks";
import React from "react";
import { Navigate } from "react-router-dom";

type ProctectRouteProps = {
  children?: React.ReactNode;
};

export const ProtectedRoute = ({ children }: ProctectRouteProps) => {
  const { isSuccess, data } = useIsLoggedIn();

  if (isSuccess && data) {
    const { authenticated, redirectTo } = data;
    if (authenticated) {
      return (
        <Navigate
          to={redirectTo ?? "/login"}
          replace
          state={{
            error: "No authentication, please complete the login process.",
          }}
        />
      );
    }
  }

  return children;
};
