"use client";

import { useEffect, useRef } from "react";

import { useLazyGetCurrentUserQuery } from "@/api/auth.api";
import { getAccessToken, getRefreshToken } from "@/lib/auth-cookies";
import { useAppDispatch } from "@/redux/hooks";
import { setCredentials } from "@/redux/slices/authSlice";

/**
 * Runs once at app boot.
 *
 * If a token cookie exists, fetches the current user from /user/profile.
 *   - Success → hydrate Redux auth state with the latest user data.
 *   - 401 → the baseQuery interceptor refreshes the token and retries.
 *           If refresh fails, the interceptor clears tokens and logs out.
 *   - Other errors → leave persisted state untouched (network blip, etc.).
 *
 * Mounted inside ReduxProvider so it runs after persist rehydration.
 * Renders nothing — pure side-effect component.
 */
export default function AuthBootstrap() {
  const dispatch = useAppDispatch();
  const [trigger] = useLazyGetCurrentUserQuery();
  const didRun = useRef(false);

  useEffect(() => {
    if (didRun.current) return;
    didRun.current = true;

    if (!getAccessToken() && !getRefreshToken()) return;

    trigger()
      .unwrap()
      .then((data) => {
        dispatch(
          setCredentials({
            user: {
              id: data.id.toString(),
              email: data.email,
              name: data.userProfile?.name,
              profileImage: data.userProfile?.profileImage?.filePath || null,
              rankName: data.userProfile?.rank?.name || "",
              isPremium: data.userSetting?.isPremium ?? false,
              billingRegion: data.userSetting?.billingRegion ?? null,
            },
          }),
        );
      })
      .catch(() => {
        // 401 path is fully handled by the baseQuery interceptor
        // (refresh → retry → logout-on-fail). Anything reaching here
        // is a transient error — keep persisted state as-is.
      });
  }, [trigger, dispatch]);

  return null;
}
