import axios from "axios";
import type {InternalAxiosRequestConfig} from "axios";

const BASE_URL: string = "http://localhost:3000/api";

const apiClient = axios.create({
	baseURL: BASE_URL,
	headers: {
		"Content-Type": "application/json",
	},
});

export const setAxiosAuthToken = (token: string | null): void => {
	if (token) {
		apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
	} else {
		delete apiClient.defaults.headers.common["Authorization"];
	}
};

apiClient.interceptors.request.use(
	(config: InternalAxiosRequestConfig) => {
		const token = localStorage.getItem("token");

		if (token && config.headers) {
			config.headers["Authorization"] = `Bearer ${token}`;
		}

		return config;
	},
	(error: any) => Promise.reject(error),
);

apiClient.interceptors.response.use(
	(response) => response,
	async (error) => {
		if (error.response?.status === 401) {
			console.error("Unauthorized - token missing or invalid");

			localStorage.removeItem("token");
			window.location.href = "/login";
		}

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

export default apiClient;
