import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import api from "../services/api";

/**
 * Protects the app.
 * - If session exists => allow rendering
 * - If not logged in => redirect to /login
 */
export default function SessionBootstrap({ children }) {
    const navigate = useNavigate();
    const [checked, setChecked] = useState(false);

    useEffect(() => {
        const run = async () => {
            try {
                const res = await api.get("/auth/session");
                if (!res?.data?.user) {
                    navigate("/login", { replace: true });
                    return;
                }
            } catch (_e) {
                navigate("/login", { replace: true });
                return;
            } finally {
                setChecked(true);
            }
        };

        run();
    }, [navigate]);

    if (!checked) return null;
    return children;
}


