import { useEffect } from "react";
import axios from "axios";
import Cookies from "js-cookie";
import { useNavigate } from "react-router-dom";

const TokenRefresher = () => {
    const navigate = useNavigate();

    useEffect(() => {
        // Function to refresh the token
        const refreshToken = async () => {
            try {
                const response = await axios.post("http://localhost:8080/api/refresh", {}, {
                    withCredentials: true,  // Make sure cookies are sent
                });
            } catch (error) {
                console.error("Failed to refresh token", error);

                // If refreshing the token fails (e.g., due to expiration), log out the user
                Cookies.remove("token"); // Optionally, clear any existing cookies
                navigate("/"); // Redirect to login page
            }
        };

        // Set the interval to call refresh every 55 minutes (3300000 ms)
        const refreshInterval = setInterval(() => {
            refreshToken();
        }, 3300000);

        // Clean up the interval on component unmount
        return () => clearInterval(refreshInterval);
    }, [navigate]); // Empty dependency array to run once when component mounts

    return null;  // This component doesn't render anything
};

export default TokenRefresher;
