import { signOut } from "next-auth/react";
import { clearAccessTokenCache } from "@/instance/getClientAccessToken";

// Parallel 401s would otherwise each fire signOut + a redirect.
let isLoggingOut = false;

export const logoutUser = async () => {
  if (isLoggingOut) return;
  isLoggingOut = true;

  try {
    // Call logout API (NO hooks!)

    // Next-auth signout
    await signOut({ redirect: false });

    // Clear browser storage
    window.localStorage.clear();

    // Clear React Query cache

    clearAccessTokenCache();

    // Only navigate if we are not already home. Redirecting to "/" while on
    // "/" is a full reload, which re-issues the request that just 401'd.
    if (window.location.pathname !== "/") {
      window.location.replace("/");
    }
  } catch (err) {
    isLoggingOut = false;
    console.error("Logout error:", err);
  }
};
