# Backend Integration - Changes Summary

This document summarizes all modifications made to integrate the Flutter frontend with the Go backend.

## 1. API Constants Updated

**File:** `lib/core/constants/api_constants.dart`

### Changes:
- ✅ Updated `baseUrl` from `'http://localhost:3000'` to `'http://localhost:8080'`
- ✅ Added `apiVersion = '/api/v1'`
- ✅ Updated all endpoint constants to include `/api/v1` prefix:
  - `loginEndpoint: '/api/v1/login'`
  - `registerEndpoint: '/api/v1/register'`
  - `profileEndpoint: '/api/v1/profile'`
  - `walletEndpoint: '/api/v1/wallet'`
  - `placeBetEndpoint: '/api/v1/bet'`
  - `cashoutEndpoint: '/api/v1/cashout'`
  - `betHistoryEndpoint: '/api/v1/bets/history'`
  - `gameHistoryEndpoint: '/api/v1/game/history'` (NEW)
  - `transactionHistoryEndpoint: '/api/v1/transactions/history'` (NEW)
- ✅ Updated WebSocket URL from `'/game'` to `/ws`
- ✅ WebSocket URL now: `'ws://localhost:8080/ws'`

## 2. Authentication Service Updated

**File:** `lib/data/services/auth_api_service.dart`

### Changes:
- ✅ Removed `logout()` method (Go backend doesn't have logout endpoint)
- ✅ Reordered methods: `register()` before `login()`
- ✅ Fixed method name: `verifyToken()` (was `verifToken`)
- ✅ Added `healthCheck()` method for backend health verification
- ✅ All methods now use updated `/api/v1` endpoints

## 3. Wallet Service Updated

**File:** `lib/data/services/wallet_api_service.dart`

### Changes:
- ✅ Updated transaction history endpoint to use `ApiConstants.transactionHistoryEndpoint`
- ✅ Endpoint now: `GET /api/v1/transactions/history`
- ✅ Supports pagination with `limit` and `offset` query parameters
- ✅ All other wallet methods updated to use new base constants

## 4. Bet Service Updated

**File:** `lib/data/services/bet_api_service.dart`

### Changes:
- ✅ Converted all request field names from camelCase to snake_case:
  - `roundId` → `round_id`
  - `autoCashout` → `auto_cashout`
  - `betId` → `bet_id`
  - `currentMultiplier` → `current_multiplier`
- ✅ Updated `placeBet()` to send snake_case fields
- ✅ Updated `cashout()` to send snake_case fields
- ✅ Added `getGameHistory()` method for `GET /api/v1/game/history`

## 5. Profile Service Updated

**File:** `lib/data/services/profile_api_service.dart`

### Changes:
- ✅ Wrapped `getStatistics()` in try-catch for graceful error handling
- ✅ Returns default empty statistics if endpoint returns error
- ✅ Updated all endpoints to use `/api/v1` prefix

## 6. WebSocket Service Enhanced

**File:** `lib/data/services/websocket_service.dart`

### Changes:
- ✅ Added automatic reconnection with exponential backoff
- ✅ Reconnection params: initial 5s, max 10 attempts
- ✅ Changed authentication mechanism from headers to message-based
- ✅ Sends auth message instead of header `Authorization`
- ✅ Added comprehensive error handling and logging
- ✅ Graceful connection cleanup and disposal

### WebSocket Message Format:
```dart
// Connection with token
{
  "type": "auth",
  "token": "jwt_token"
}

// Receiving events
{
  "type": "multiplier_update",
  "round_id": "string",
  "current_multiplier": 1.45,
  "timestamp": "2024-01-01T00:00:00Z"
}
```

## 7. API Service Error Handling

**File:** `lib/data/services/api_service.dart`

### Changes:
- ✅ Created `AuthenticationException` class for auth errors
- ✅ Enhanced error interceptor to handle 401 responses:
  - Clears stored token automatically
  - Clears user data from local storage
  - Throws `AuthenticationException` for app-level handling
- ✅ Updated all request methods to catch and re-throw with proper exception type
- ✅ 401 errors now trigger automatic logout and redirect to login

### Error Handling Flow:
```
API Request → 401 Response
    ↓
Interceptor clears local storage
    ↓
AuthenticationException thrown
    ↓
Caught by caller
    ↓
App redirects to login screen
```

## 8. Authentication Repository Updated

**File:** `lib/data/repositories/auth_repository.dart`

### Changes:
- ✅ Updated `logout()` method:
  - Removed backend API call (not available in Go backend)
  - Now only clears local user data
  - Supports local-only logout functionality

```dart
/// Logout user (Go backend doesn't have logout endpoint)
Future<void> logout() async {
  // Clear all local user data
  await localStorageService.clearAllUserData();
}
```

## 9. App Router Enhanced

**File:** `lib/core/routes/app_router.dart`

### Changes:
- ✅ Added `navigatorKey` for context-free navigation
- ✅ Enhanced redirect logic to check authentication state
- ✅ Added logic to redirect to login if token is null
- ✅ Added logic to redirect logged-in users away from auth screens
- ✅ Added `AuthErrorHandling` extension for easy logout navigation

### New Extension:
```dart
extension AuthErrorHandling on BuildContext {
  void handleAuthError() {
    GoRouter.of(this).go(RouteNames.login);
  }
}
```

## 10. Models Compatibility Notes

**Files:** `lib/domain/models/*.dart`

### Status: ⚠️ REQUIRES VERIFICATION

The frontend models currently use camelCase fields in their Dart code, but the Go backend sends snake_case JSON fields. The `fromJson()` methods need to handle this mapping.

### Required Updates:
```dart
// Current (will fail):
factory BetModel.fromJson(Map<String, dynamic> json) {
  return BetModel(
    roundId: json['roundId'],  // ❌ Backend sends 'round_id'
  );
}

// Should be:
factory BetModel.fromJson(Map<String, dynamic> json) {
  return BetModel(
    roundId: json['round_id'],  // ✅ Matches Go backend
  );
}
```

### Models to Check:
- [ ] `BetModel` - roundId, autoCashout, betId, currentMultiplier
- [ ] `GameRoundModel` - finalMultiplier, crashedAt, startedAt, endedAt
- [ ] `TransactionModel` - balanceBefore, balanceAfter
- [ ] `WalletModel` - lastUpdated
- [ ] `UserModel` - createdAt

## Complete Integration Checklist

### ✅ Completed Tasks:
- [x] API constants updated to `/api/v1` with correct base URL
- [x] Authentication service aligned with Go backend routes
- [x] Wallet service updated with correct endpoints
- [x] Bet service: field names converted to snake_case
- [x] Profile service: error handling for optional endpoints
- [x] WebSocket service: reconnection logic and proper auth
- [x] API service: 401 error handling with auto-logout
- [x] Auth repository: logout without backend call
- [x] Router: enhanced error handling and redirect logic
- [x] Documentation: comprehensive backend integration guide

### ⏳ Pending Tasks:
- [ ] Verify model `fromJson()` methods handle snake_case fields
- [ ] Test all API endpoints against running backend
- [ ] Test WebSocket connection and event handling
- [ ] Test 401 error handling and auto-redirect
- [ ] Test complete auth flow (register, login, logout)
- [ ] Test betting flow (place bet, cashout, history)
- [ ] Verify error messages match backend responses
- [ ] Test pagination on history endpoints

## API Field Name Mapping Reference

### Snake Case Conversions Implemented:

| Dart Field | JSON Field | Service | Status |
|-----------|-----------|---------|--------|
| `roundId` | `round_id` | bet_api_service | ✅ |
| `autoCashout` | `auto_cashout` | bet_api_service | ✅ |
| `betId` | `bet_id` | bet_api_service | ✅ |
| `currentMultiplier` | `current_multiplier` | bet_api_service | ✅ |
| `finalMultiplier` | `final_multiplier` | Models | ⚠️ PENDING |
| `crashedAt` | `crashed_at` | Models | ⚠️ PENDING |
| `startedAt` | `started_at` | Models | ⚠️ PENDING |
| `endedAt` | `ended_at` | Models | ⚠️ PENDING |
| `createdAt` | `created_at` | Models | ⚠️ PENDING |
| `balanceBefore` | `balance_before` | Models | ⚠️ PENDING |
| `balanceAfter` | `balance_after` | Models | ⚠️ PENDING |
| `lastUpdated` | `last_updated` | Models | ⚠️ PENDING |

## Testing Against Go Backend

### Prerequisites:
- Go backend running on `http://localhost:8080`
- Database seeded with test data
- JWT secret configured in backend

### Quick Test Sequence:
1. **Register**: POST `/api/v1/register` with new credentials
2. **Login**: POST `/api/v1/login` with registered credentials
3. **Verify Token**: GET `/api/v1/profile` with auth header
4. **Get Wallet**: GET `/api/v1/wallet` with auth header
5. **Place Bet**: POST `/api/v1/bet` with snake_case fields
6. **Cashout**: POST `/api/v1/cashout` with snake_case fields
7. **History**: GET `/api/v1/bets/history` with pagination
8. **WebSocket**: Connect to `ws://localhost:8080/ws` and receive events

## Next Steps

1. **Immediate (Must Do):**
   - Update all model `fromJson()` methods to handle snake_case fields
   - Verify model names match backend response format
   
2. **Before Production:**
   - Test complete integration with running backend
   - Verify all error scenarios are handled
   - Test WebSocket reconnection behavior
   - Test JWT token expiry handling
   - Verify pagination works on all history endpoints

3. **Nice-to-Have:**
   - Implement token refresh mechanism
   - Add request/response logging for debugging
   - Cache frequently used data
   - Add offline support for history screens