import axiosAPI from "./axios";
import { refreshToken } from "@/actions/auth";

const handleRequest = async (request) => {
	try {
		return await request();
	} catch (error) {
		if (error?.response?.status === 401) {
			try {
				const token = await refreshToken();
				if (token.success) {
					axiosAPI.defaults.headers.Authorization = `Bearer ${token.access_token}`;
					return await request();
				}
				return false;
			} catch (error) {
				console.log(error);
				return false;
			}
		}
		console.log(error);
		return false;
	}
};

export const get = async (url, config = null) => {
	try {
		const request = () => axiosAPI.get(url, config);
		const res = await handleRequest(request);
		return res;
	} catch (error) {
		console.log(error);
		return false;
	}
};

export const post = async (url, data, config = null) => {
	try {
		const request = () => axiosAPI.post(url, data, config);
		const res = await handleRequest(request);
		return res;
	} catch (error) {
		console.log(error);
		return false;
	}
};

export const put = async (url, data, config = null) => {
	try {
		const request = () => axiosAPI.put(url, data, config);
		const res = await handleRequest(request);
		return res;
	} catch (error) {
		console.log(error);
		return false;
	}
};

export const del = async (url, config = null) => {
	try {
		const request = () => axiosAPI.delete(url, config);
		const res = await handleRequest(request);
		return res;
	} catch (error) {
		console.log(error);
		return false;
	}
};
