import { LOG } from "@logger";
import axios from "axios";
import type { AppReduxStore } from "@/redux";

const log = LOG.extend("AxiosInstance");

let store: AppReduxStore;

export const injectStoreIntoAxiosInstance = (_store: AppReduxStore) => {
	store = _store;
};

export const axiosInstance = axios.create({
	// biome-ignore lint/style/useNamingConvention: <Axios config require baseURL.>
	baseURL: process.env.EXPO_PUBLIC_API_URL,
});

axiosInstance.interceptors.request.use(
	(config) => {
		config.headers.authorization = `Bearer ${store.getState().auth.token.access}`;
		config.auth = {
			username: "admin",
			password: "admin",
		};

		log.http({ "Request Interceptor Config": config });
		return config;
	},
	(error) => {
		log.error({ "Request Interceptor Error": error });
		return Promise.reject(error);
	},
);

axiosInstance.interceptors.response.use(
	(response) => {
		log.http({ "Response Interceptor Response Data": response.data });
		return response;
	},
	(error) => {
		log.error({ "Response Interceptor Error": error });

		if (error.response) {
			const { status, data } = error.response;
			switch (status) {
				case 400:
					log.error({ message: "Bad Request", status, data });
					break;
				case 401:
					log.error({
						message: "Unauthorized, setting auth status to False",
						status,
						data,
					});
					// Handle unauthorized access, e.g., redirect to login
					break;
				case 404:
					log.error({ message: "Not Found", status, data });
					break;
				case 500:
					log.error("Server Error:", "Please try again later");
					// Display a user-friendly message, log the error
					break;
				default:
					log.error({ message: "Unknown Error", status, data });
					break;
			}
		}

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