"use client";

import { useEffect, useRef } from "react";
import Cookies from "js-cookie";
import { useAppDispatch, useAppSelector } from "@/hooks/useRedux";
import { fetchCurrentUser } from "@/store/slices/authSlice";
import { COOKIE_KEYS } from "@/constants";

export function AuthInitializer({ children }: { children: React.ReactNode }) {
  const dispatch = useAppDispatch();
  const { isAuthenticated, user } = useAppSelector((s) => s.auth);
  const hasFetched = useRef(false);

  useEffect(() => {
    const token = Cookies.get(COOKIE_KEYS.ACCESS_TOKEN);
    if (token && isAuthenticated && !user && !hasFetched.current) {
      hasFetched.current = true;
      dispatch(fetchCurrentUser());
    }
  }, [dispatch, isAuthenticated, user]);

  return <>{children}</>;
}
