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

import { useAccounts } from "@/contexts/AccountsContext";
import { useAuthClient, useSession } from "@/contexts/AuthContext";
import { performAuthReset } from "@/lib/auth-session";
import { isRateLimitError } from "@/lib/trpc-errors";

/** Refetch auth session when the app returns to the foreground. */
export function SessionSync() {
  const authClient = useAuthClient();
  const { activeAccountId, clearActiveAccount } = useAccounts();
  const { data: session, refetch } = useSession();
  const wasBackgrounded = useRef(false);
  const resettingRef = 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 (async () => {
        await refetch();
        const next = await authClient.getSession();
        if (next.error && isRateLimitError(next.error)) return;
        if (next.data?.user) return;
        if (!session?.user || resettingRef.current) return;

        resettingRef.current = true;
        try {
          await performAuthReset({
            authClient,
            clearActiveAccount,
            activeAccountId,
            refetchSession: refetch,
          });
        } finally {
          resettingRef.current = false;
        }
      })();
    });

    return () => subscription.remove();
  }, [authClient, refetch, session?.user, activeAccountId, clearActiveAccount]);

  return null;
}
