import type { LoginCredentials, RegisterData, AuthResponse, ApiResponse } from '@avanzacast/shared-types'; import { getAuthHeader } from './auth'; const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:4000/api/v1'; /** * Cliente HTTP para hacer peticiones a la API */ class ApiClient { private baseUrl: string; constructor(baseUrl: string) { this.baseUrl = baseUrl; } private async request( endpoint: string, options: RequestInit = {} ): Promise> { const url = `${this.baseUrl}${endpoint}`; const headers = { 'Content-Type': 'application/json', ...getAuthHeader(), ...options.headers, }; try { const response = await fetch(url, { ...options, headers, }); const data = await response.json(); if (!response.ok) { return { success: false, error: { code: data.code || 'UNKNOWN_ERROR', message: data.message || 'An error occurred', details: data.details, }, }; } return { success: true, data, }; } catch (error) { return { success: false, error: { code: 'NETWORK_ERROR', message: error instanceof Error ? error.message : 'Network error', }, }; } } async get(endpoint: string): Promise> { return this.request(endpoint, { method: 'GET' }); } async post(endpoint: string, data?: any): Promise> { return this.request(endpoint, { method: 'POST', body: data ? JSON.stringify(data) : undefined, }); } async put(endpoint: string, data?: any): Promise> { return this.request(endpoint, { method: 'PUT', body: data ? JSON.stringify(data) : undefined, }); } async delete(endpoint: string): Promise> { return this.request(endpoint, { method: 'DELETE' }); } // Auth endpoints async login(credentials: LoginCredentials): Promise> { return this.post('/auth/login', credentials); } async register(data: RegisterData): Promise> { return this.post('/auth/register', data); } async logout(): Promise> { return this.post('/auth/logout'); } async refreshToken(refreshToken: string): Promise> { return this.post('/auth/refresh', { refreshToken }); } async getProfile(): Promise> { return this.get('/auth/profile'); } } // Instancia Ășnica del cliente API export const apiClient = new ApiClient(API_BASE_URL); // Exportar cliente por defecto export default apiClient;