const apiClient = () => {
    const token = localStorage.getItem("token_session");
    const urlBase = "https://m2mcloud.awproyectos.com"; // colocar el dominio para producción

    const fetchData = async (url, method = "GET", body = null, headers = {}, isFormData = false) => {
        try {
            const options = {
                method,
                headers: {
                    "Authorization": `Bearer ${token}`,
                    ...headers,
                },
            };
            
            // Para solicitudes GET, establecer el Content-Type
            if(method === "GET") {
               options.headers["Content-Type"] = "application/json";
            }

            // Si no es FormData, usar JSON normal
            if (body && method !== "GET") {
                if (isFormData) {
                    options.body = body; // ya es FormData
                } else {
                    options.headers["Content-Type"] = "application/json";
                    options.body = JSON.stringify(body);
                }
            }

            const response = await fetch(urlBase + url, options);

            if (!response.ok) {
                throw new Error(`Error ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error("Error fetching data:", error);
            return { success: false, message: error.message };
        }
    };

    return { fetchData };
};

export default apiClient;
