import AsyncStorage from '@react-native-async-storage/async-storage'; import { API_CONFIG } from '../constants/api'; class AuthService { async getStoredToken() { try { return await AsyncStorage.getItem('auth_token'); } catch (error) { return null; } } async makeRequest(endpoint, data, requiresAuth = false, method = 'POST') { const fullUrl = `${API_CONFIG.BASE_URL}${endpoint}`; const requestId = Math.random().toString(36).substr(2, 9); try { const headers = { ...API_CONFIG.HEADERS, }; // Auto-include token for authenticated requests if (requiresAuth) { const token = await this.getStoredToken(); if (token) { headers.Authorization = `Bearer ${token}`; } } // Log request details console.log(`\nšŸš€ [${requestId}] API REQUEST`); console.log(`šŸ“ URL: ${method} ${fullUrl}`); console.log(`šŸ” Auth Required: ${requiresAuth}`); console.log(`šŸ“ Headers:`, { ...headers, Authorization: headers.Authorization ? `Bearer ${headers.Authorization.slice(-10)}...` : 'None' }); if (data) { console.log(`šŸ“¦ Body:`, data); } console.log(`ā° Time: ${new Date().toISOString()}`); const startTime = Date.now(); const response = await fetch(fullUrl, { method, headers, body: data ? JSON.stringify(data) : undefined, }); const endTime = Date.now(); const duration = endTime - startTime; const result = await response.json(); // Log response details console.log(`\nāœ… [${requestId}] API RESPONSE`); console.log(`šŸ“Š Status: ${response.status} ${response.statusText}`); console.log(`ā±ļø Duration: ${duration}ms`); console.log(`šŸ“„ Response:`, result); if (!response.ok) { console.log(`āŒ [${requestId}] API ERROR`); console.log(`šŸ”“ Status: ${response.status}`); console.log(`šŸ’¬ Error Message:`, result.message || 'Unknown error'); // Handle token expiration if (response.status === 401 && requiresAuth) { console.log(`šŸ”“ [${requestId}] TOKEN EXPIRED - Clearing storage`); await AsyncStorage.removeItem('auth_token'); await AsyncStorage.removeItem('user_data'); throw new Error('Session expired. Please login again.'); } throw new Error(result.message || 'An error occurred'); } console.log(`✨ [${requestId}] REQUEST COMPLETED SUCCESSFULLY\n`); return result; } catch (error) { console.log(`\nšŸ’„ [${requestId}] API REQUEST FAILED`); console.log(`šŸ“ URL: ${method} ${fullUrl}`); console.log(`šŸ”“ Error:`, error.message); console.log(`šŸ“… Time: ${new Date().toISOString()}\n`); throw new Error(error.message || 'Network error'); } } async login(phone, password) { return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.LOGIN, { phone: parseInt(phone), password, }); } async register(phone, name, password) { return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.REGISTER, { phone: parseInt(phone), name, password, }); } async verify(phone, code) { return this.makeRequest(API_CONFIG.ENDPOINTS.AUTH.VERIFY, { phone: parseInt(phone), code: parseInt(code), }); } // Authenticated API methods async getProfile() { return this.makeRequest('/profile', null, true, 'GET'); } async updateProfile(data) { return this.makeRequest('/profile', data, true, 'POST'); } async getTransactions(page = 1, limit = 20) { return this.makeRequest(`/user/transactions?page=${page}&limit=${limit}`, null, true, 'GET'); } async getBalance() { return this.makeRequest('/user/balance', null, true, 'GET'); } async transferMoney(data) { return this.makeRequest('/user/transfer', data, true); } async payBill(data) { return this.makeRequest('/user/pay-bill', data, true); } async getCards() { return this.makeRequest('/user/cards', null, true, 'GET'); } async addCard(data) { return this.makeRequest('/user/cards', data, true); } async blockCard(cardId) { return this.makeRequest(`/user/cards/${cardId}/block`, null, true); } async unblockCard(cardId) { return this.makeRequest(`/user/cards/${cardId}/unblock`, null, true); } async changePassword(currentPassword, newPassword) { return this.makeRequest('/user/change-password', { current_password: currentPassword, new_password: newPassword, }, true); } async deleteAccount() { return this.makeRequest('/user/delete-account', null, true, 'DELETE'); } } export default new AuthService();