"use client";

import * as React from "react";
import equal from "fast-deep-equal";
import { useGetProfileQuery } from "@/api/rtk/auth-api";
import { useAuthToken } from "@/hooks/use-auth-token";
import { useAppDispatch, useAppStore } from "@/store/hooks";
import type { RootState } from "@/store";
import { setProfileCacheData } from "@/store/slices/profile-cache-slice";

function selectProfileCacheData(state: RootState) {
  /** `profileCache` can be missing briefly before redux-persist rehydrates. */
  return state.profileCache?.data ?? null;
}

/**
 * Mirrors RTK Query `getProfile` (`/auth/profile`) into {@link profileCache},
 * dispatching only when the payload differs from Redux (fast-deep-equal).
 */
export function ProfileCacheSync() {
  const { token } = useAuthToken();
  const dispatch = useAppDispatch();
  const store = useAppStore();
  const { data } = useGetProfileQuery(undefined, { skip: !token });

  React.useLayoutEffect(() => {
    if (!token) return;
    if (data === undefined) return;
    const prev = selectProfileCacheData(store.getState());
    if (!equal(prev, data)) {
      dispatch(setProfileCacheData(data));
    }
  }, [token, data, dispatch, store]);

  return null;
}
