import { DOMAIN, TOKEN } from "@/constants";
import { removeStorageItem } from "@/utils/storage";
import { Router } from "expo-router";

let routerInstance: Router | null = null;

/**
 * Set router instance để dùng trong non-component context
 */
export const setRouterInstance = (router: Router) => {
  routerInstance = router;
};

/**
 * Handle 401 error - redirect to login
 */
export const handle401 = () => {
  if (routerInstance) {
    removeStorageItem(TOKEN);
    // Cancel all pending requests to prevent further API calls
    if (typeof window !== "undefined" && (window as any).axiosAbortController) {
      (window as any).axiosAbortController.abort();
    }
    routerInstance.navigate("/auth/login");
  } else {
    console.warn("Router instance not set, cannot redirect to login");
  }
};

/**
 * Clear router instance (optional, for cleanup)
 */
export const clearRouterInstance = () => {
  routerInstance = null;
};
