import { useEffect, useRef } from "react";
import { AppState, type AppStateStatus } from "react-native";

import { useSession } from "@/contexts/AuthContext";

/** Refetch auth session when the app returns to the foreground. */
export function SessionSync() {
  const { refetch } = useSession();
  const wasBackgrounded = useRef(false);

  useEffect(() => {
    const subscription = AppState.addEventListener("change", (nextState: AppStateStatus) => {
      if (nextState === "background" || nextState === "inactive") {
        wasBackgrounded.current = true;
        return;
      }

      if (nextState !== "active" || !wasBackgrounded.current) return;
      wasBackgrounded.current = false;
      void refetch();
    });

    return () => subscription.remove();
  }, [refetch]);

  return null;
}
