import axios from "axios";
import { router } from "expo-router";

type ApiConfig = {
	serverIp: string;
	serverPort: string | number;
};

let currentConfig: ApiConfig | null = null;

export function setApiConfig(config: ApiConfig) {
	currentConfig = config;
}

function getBaseUrl() {
	if (!currentConfig) {
		throw new Error("API config not initialized");
	}
	console.log(
		`http://${currentConfig.serverIp}:${currentConfig.serverPort}/lst/api`,
	);
	return `http://${currentConfig.serverIp}:${currentConfig.serverPort}/lst/api`;
}

export const api = axios.create({
	timeout: 15000,
});

api.interceptors.request.use((config) => {
	config.baseURL = getBaseUrl();

	return config;
});

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;

		// unauthorized
		if (error.response?.status === 401) {
			router.replace("/login");
		}

		// forbidden
		if (error.response?.status === 403) {
			router.replace("/");
		}

		// app/server offline
		if (isNetworkError) {
			router.replace("/");
		}

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