const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.approagency.ir/api'; interface ApiOptions extends RequestInit { token?: string; } class ApiClient { private async request( endpoint: string, options: ApiOptions = {} ): Promise { const { token, ...fetchOptions } = options; const headers: Record = { ...(options.headers as Record || {}), }; // Don't set Content-Type for FormData (browser will set it automatically with boundary) if (!(options.body instanceof FormData)) { headers['Content-Type'] = 'application/json'; } if (token) { headers['Authorization'] = `Bearer ${token}`; } const response = await fetch(`${API_BASE_URL}${endpoint}`, { ...fetchOptions, headers, }); if (!response.ok) { const error = await response.json().catch(() => ({})); throw new Error(error.message || 'API request failed'); } return response.json(); } async post(endpoint: string, data: any, token?: string): Promise { const body = data instanceof FormData ? data : JSON.stringify(data); return this.request(endpoint, { method: 'POST', body, token, }); } async get(endpoint: string, token?: string): Promise { return this.request(endpoint, { method: 'GET', token, }); } async put(endpoint: string, data: any, token?: string): Promise { const body = data instanceof FormData ? data : JSON.stringify(data); return this.request(endpoint, { method: 'PUT', body, token, }); } async delete(endpoint: string, data?: any, token?: string): Promise { const options: ApiOptions = { method: 'DELETE', token, }; // Handle DELETE with body if data is provided if (data) { options.body = data instanceof FormData ? data : JSON.stringify(data); // Don't set Content-Type for FormData if (!(data instanceof FormData)) { options.headers = { 'Content-Type': 'application/json', }; } } return this.request(endpoint, options); } // Convenience method for DELETE with JSON body async deleteWithBody(endpoint: string, data: any, token?: string): Promise { return this.delete(endpoint, data, token); } async patch(endpoint: string, data: any, token?: string): Promise { const body = data instanceof FormData ? data : JSON.stringify(data); return this.request(endpoint, { method: 'PATCH', body, token, }); } } export const apiClient = new ApiClient();