import { LOG } from "@logger";
import axios, { type AxiosError, type AxiosResponse } from "axios";

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

const baseUrl = process.env.EXPO_PUBLIC_API_URL;

// biome-ignore lint/style/useNamingConvention: <baseURL is not for me to change.>
const client = axios.create({ baseURL: baseUrl });

const axiosRequest = async <T>({ ...options }): Promise<T> => {
	// console.log("base Url", baseUrl);
	// client.defaults.headers.common.Authorization = `Bearer ${""}`;
	// client.defaults.headers.common['Content-Type'] = 'application/json';
	// console.log("client default", client.defaults);
	// console.log("client datas", client.defaults.data);
	log.debug("Base url :: ", client.getUri());
	log.debug("RequestOptions :: ", options);

	const onSuccess = (response: T) => {
		return response;
	};
	const onError = (error: AxiosError) => {
		log.error(error);
		throw error;
	};

	try {
		const response: AxiosResponse<T> = await client({ ...options });
		return onSuccess(response.data);
	} catch (error: unknown) {
		if (axios.isAxiosError(error)) {
			log.error("axiosRequest | Response :: ", JSON.stringify(error.response, null, 2));
			// log.error("Axios RequestError Reponse message:: ", error.message);
			// log.error("Axios RequestError Reponse name:: ", error.response?.data);
		} else {
			log.error("axiosRequest | General RequestError :: ", JSON.stringify(error, null, 2));
		}
		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
		return onError(error as any);
	}
};

export default axiosRequest;
