import { useToast } from './useToast' export function useApi() { const { showSuccess, showError, showInfo } = useToast() const API_BASE_URL = process.env.NUXT_PUBLIC_API_BASE_URL || 'http://localhost:3000/api' const API_TIMEOUT = parseInt(process.env.NUXT_PUBLIC_API_TIMEOUT || '30000') const apiCall = async (endpoint, options = {}) => { const url = `${API_BASE_URL}${endpoint}` const defaultOptions = { headers: { 'Content-Type': 'application/json', }, } // Ajouter un timeout à la requête const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT) try { const response = await fetch(url, { ...defaultOptions, ...options, signal: controller.signal }) clearTimeout(timeoutId) if (response.ok) { const data = await response.json() return { success: true, data } } else { const errorData = await response.json().catch(() => ({})) const errorMessage = errorData.message || `Erreur ${response.status}: ${response.statusText}` showError(errorMessage) return { success: false, error: errorMessage, status: response.status } } } catch (error) { clearTimeout(timeoutId) const errorMessage = error.name === 'AbortError' ? 'Timeout de la requête' : error.message || 'Erreur réseau' showError(`Erreur réseau: ${errorMessage}`) return { success: false, error: errorMessage } } } const get = async (endpoint) => { return apiCall(endpoint, { method: 'GET' }) } const post = async (endpoint, data) => { return apiCall(endpoint, { method: 'POST', body: JSON.stringify(data) }) } const patch = async (endpoint, data) => { return apiCall(endpoint, { method: 'PATCH', body: JSON.stringify(data) }) } const del = async (endpoint) => { return apiCall(endpoint, { method: 'DELETE' }) } return { apiCall, get, post, patch, delete: del } }