import { useLogto } from "@logto/react";
import { useCallback, useEffect, useState } from "react"
import { AUTH_CALLBACK_URL } from "../utils/front";


const useAutoLogin = () => {
  const { isAuthenticated, getAccessToken } = useLogto();
  const [isAuthExpired, setIsAuthExpired] = useState(false);
  const { signIn } = useLogto();
  const autoSignIn = useCallback((redirect?: string) => {
    sessionStorage.setItem('redirect', redirect ?? window.location.pathname);
    signIn(AUTH_CALLBACK_URL);
  }, []);
  useEffect(() => {
    if (isAuthenticated) {
      getAccessToken().then(e => {
        if (!e) setIsAuthExpired(true); // Assuming
      });
    }
  },  [isAuthenticated]);
  return { autoSignIn, isAuthExpired };
}

export default useAutoLogin;
