import type { Router } from "@tanstack/react-router";
import axios from "axios";
import { toast } from "sonner";

let appRouter: Router<any, any> | null = null;

export function setApiRouter(router: Router<any, any>) {
	appRouter = router;
}

export const api = axios.create({
	baseURL: "/lst/api",
	withCredentials: true,
	timeout: 15000,
});

api.interceptors.response.use(
	(response) => response,
	(error) => {
		const isNetworkError =
			error.code === "ERR_NETWORK" ||
			error.code === "ECONNABORTED" ||
			error.message === "Network Error" ||
			error.message === "Failed to fetch" ||
			!error.response;

		if (error.response?.status === 403) {
			// redirect, toast, or show forbidden page
			toast.error("Unauthorized to be here");

			appRouter?.navigate({ to: "/forbidden", replace: true });
		}

		if (error.response?.status === 401) {
			// redirect, toast, or show forbidden page
			toast.error("Unauthorized to be here");

			appRouter?.navigate({ to: "/login", replace: true });
		}

		if (isNetworkError) {
			appRouter?.navigate({ to: "/app-down", replace: true });
		}

		return Promise.reject(error);
	},
);
