import axios from 'axios'; import type { Transaction, Wallet, Exchange, Loan } from './types'; const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api'; const apiClient = axios.create({ baseURL: API_URL, headers: { 'Content-Type': 'application/json' } }); // Add a request interceptor to add the auth token apiClient.interceptors.request.use( (config) => { const token = localStorage.getItem('auth_token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => Promise.reject(error) ); // Add a response interceptor for generic error handling apiClient.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401 || error.response?.status === 403) { // Token expired or unauthorized, logout localStorage.removeItem('auth_token'); localStorage.removeItem('auth_username'); window.location.href = '/login'; } console.error('API Error:', error.response?.data || error.message); return Promise.reject(error); } ); export const api = { getRates: () => apiClient.get>('/rates').then(res => res.data), getWallets: () => apiClient.get('/wallets').then(res => res.data), getTransactions: () => apiClient.get('/transactions').then(res => res.data), createTransaction: (data: Omit) => apiClient.post('/transactions', data).then(res => res.data), getExchanges: () => apiClient.get('/exchanges').then(res => res.data), createExchange: (data: Omit) => apiClient.post('/exchanges', data).then(res => res.data), getLoans: () => apiClient.get('/loans').then(res => res.data), createLoan: (data: Omit) => apiClient.post('/loans', data).then(res => res.data), updateLoan: (id: number, data: Omit) => apiClient.put(`/loans/${id}`, data).then(res => res.data), deleteLoan: (id: number) => apiClient.delete(`/loans/${id}`).then(res => res.data), payLoan: (id: number, amount: number) => apiClient.post(`/loans/${id}/pay`, { amount }).then(res => res.data), getDashboardAnalytics: () => apiClient.get('/analytics/dashboard').then(res => res.data) };