import axios, { AxiosInstance, AxiosResponse } from 'axios'; import { FindNearbyParkingRequest, FindNearbyParkingResponse, ParkingLot, UpdateAvailabilityRequest } from '@/types'; class APIClient { private client: AxiosInstance; constructor() { this.client = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api', timeout: 30000, headers: { 'Content-Type': 'application/json', }, }); // Request interceptor this.client.interceptors.request.use( (config) => { // Add auth token if available const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => Promise.reject(error) ); // Response interceptor this.client.interceptors.response.use( (response: AxiosResponse) => response, (error) => { if (error.response?.status === 401) { // Handle unauthorized if (typeof window !== 'undefined') { localStorage.removeItem('auth_token'); window.location.href = '/login'; } } return Promise.reject(error); } ); } // Parking endpoints async findNearbyParking(request: FindNearbyParkingRequest): Promise { const response = await this.client.post('/parking/nearby', request); return response.data; } async getAllParkingLots(): Promise { const response = await this.client.get('/parking'); return response.data; } async getParkingLotById(id: number): Promise { const response = await this.client.get(`/parking/${id}`); return response.data; } async updateParkingAvailability(id: number, data: UpdateAvailabilityRequest): Promise { const response = await this.client.put(`/parking/${id}/availability`, data); return response.data; } async getPopularParkingLots(limit?: number): Promise { const response = await this.client.get('/parking/popular', { params: { limit } }); return response.data; } // Health endpoint async getHealth(): Promise<{ status: string; timestamp: string }> { const response = await this.client.get('/health'); return response.data; } } // Create singleton instance export const apiClient = new APIClient(); // Export individual service functions for convenience export const parkingService = { findNearby: (request: FindNearbyParkingRequest) => apiClient.findNearbyParking(request), getAll: () => apiClient.getAllParkingLots(), getById: (id: number) => apiClient.getParkingLotById(id), updateAvailability: (id: number, data: UpdateAvailabilityRequest) => apiClient.updateParkingAvailability(id, data), getPopular: (limit?: number) => apiClient.getPopularParkingLots(limit), }; export const healthService = { getHealth: () => apiClient.getHealth(), };