'use client'
import { useAuth } from "@/lib/contexts/auth";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";

function WithAuthMiddleware({ children }) {
    const router = useRouter()
    const pathName = usePathname()
    const { isAuth, initAuthState } = useAuth();

    useEffect(() => {
        if (!initAuthState) return
        if (!isAuth) {
            router.replace(`${process.env.NEXT_PUBLIC_API_URL}/login?_back=${encodeURIComponent(pathName)}`)
        }
    }, [isAuth, initAuthState])

    if (!initAuthState || !isAuth) return null;
    return <>{children}</>
}

export default WithAuthMiddleware