# Backend Integration Guide

This document outlines how the Flutter frontend integrates with the Go backend for the Aviator betting game.

## Backend Configuration

**Base URL:** `http://localhost:8080`
**API Version:** `/api/v1`
**WebSocket URL:** `ws://localhost:8080/ws`

## Authentication

### JWT Token Handling

The backend uses JWT authentication with Bearer tokens. The frontend automatically:

1. **Stores tokens** via `LocalStorageService` after login/registration
2. **Includes tokens** in all API requests via the Authorization header (`Bearer {token}`)
3. **Handles 401 responses** by clearing local storage and redirecting to login

### Token Interceptor

The `ApiService` includes automatic token injection:

```dart
// Automatically added to all requests
headers['Authorization'] = 'Bearer $token'
```

### Authentication Error Handling

When a 401 Unauthorized error is received:

1. Local token and user data are automatically cleared
2. `AuthenticationException` is thrown
3. The app redirects to the login screen
4. User must re-authenticate

## API Endpoints

All endpoints use `/api/v1` prefix and snake_case field names.

### Authentication Endpoints

#### Register User
```
POST /api/v1/register
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "securepassword"
}

Response:
{
  "token": "jwt_token_here",
  "user": {
    "id": "user_id",
    "name": "John Doe",
    "email": "john@example.com",
    "balance": 1000.00,
    "created_at": "2024-01-01T00:00:00Z"
  }
}
```

#### Login
```
POST /api/v1/login
Content-Type: application/json

{
  "email": "john@example.com",
  "password": "securepassword"
}

Response:
{
  "token": "jwt_token_here",
  "user": {
    "id": "user_id",
    "name": "John Doe",
    "email": "john@example.com",
    "balance": 1000.00,
    "created_at": "2024-01-01T00:00:00Z"
  }
}
```

#### Health Check
```
GET /api/v1/health

Response:
{
  "status": "healthy"
}
```

### Profile Endpoints

#### Get Profile
```
GET /api/v1/profile
Authorization: Bearer {token}

Response:
{
  "id": "user_id",
  "name": "John Doe",
  "email": "john@example.com",
  "balance": 1000.00,
  "created_at": "2024-01-01T00:00:00Z"
}
```

#### Update Profile
```
PUT /api/v1/profile
Authorization: Bearer {token}
Content-Type: application/json

{
  "name": "John Doe Updated",
  "email": "newemail@example.com"
}

Response:
{
  "id": "user_id",
  "name": "John Doe Updated",
  "email": "newemail@example.com",
  "balance": 1000.00,
  "created_at": "2024-01-01T00:00:00Z"
}
```

### Wallet Endpoints

#### Get Wallet
```
GET /api/v1/wallet
Authorization: Bearer {token}

Response:
{
  "id": "wallet_id",
  "user_id": "user_id",
  "balance": 1000.00,
  "currency": "USD",
  "last_updated": "2024-01-01T00:00:00Z"
}
```

#### Transaction History
```
GET /api/v1/transactions/history?page=1&limit=10
Authorization: Bearer {token}

Response:
{
  "transactions": [
    {
      "id": "transaction_id",
      "user_id": "user_id",
      "type": "bet",
      "amount": 50.00,
      "balance_before": 1000.00,
      "balance_after": 950.00,
      "description": "Bet placed",
      "timestamp": "2024-01-01T00:00:00Z"
    }
  ],
  "total": 100,
  "page": 1,
  "limit": 10
}
```

### Betting Endpoints

#### Place Bet
```
POST /api/v1/bet
Authorization: Bearer {token}
Content-Type: application/json

{
  "round_id": "round_id",
  "amount": 50.00,
  "auto_cashout": 2.5
}

Response:
{
  "id": "bet_id",
  "user_id": "user_id",
  "round_id": "round_id",
  "amount": 50.00,
  "auto_cashout": 2.5,
  "status": "active",
  "placed_at": "2024-01-01T00:00:00Z"
}
```

#### Cashout Bet
```
POST /api/v1/cashout
Authorization: Bearer {token}
Content-Type: application/json

{
  "bet_id": "bet_id",
  "current_multiplier": 1.85
}

Response:
{
  "id": "bet_id",
  "user_id": "user_id",
  "status": "cashed_out",
  "cashout_multiplier": 1.85,
  "winnings": 92.50,
  "cashed_out_at": "2024-01-01T00:00:00Z"
}
```

#### Bet History
```
GET /api/v1/bets/history?page=1&limit=20
Authorization: Bearer {token}

Response:
{
  "bets": [
    {
      "id": "bet_id",
      "round_id": "round_id",
      "amount": 50.00,
      "status": "won",
      "final_multiplier": 2.5,
      "winnings": 125.00,
      "placed_at": "2024-01-01T00:00:00Z",
      "ended_at": "2024-01-01T00:00:15Z"
    }
  ],
  "total": 150,
  "page": 1,
  "limit": 20
}
```

#### Game History
```
GET /api/v1/game/history?page=1&limit=50
Authorization: Bearer {token}

Response:
{
  "rounds": [
    {
      "id": "round_id",
      "final_multiplier": 2.45,
      "crashed_at": 2.45,
      "started_at": "2024-01-01T00:00:00Z",
      "ended_at": "2024-01-01T00:00:15Z"
    }
  ],
  "total": 500,
  "page": 1,
  "limit": 50
}
```

## WebSocket Communication

### Connection

The frontend automatically connects to the WebSocket when needed:

```dart
// Connect with authentication
await webSocketService.connect(token: authToken);
```

### Message Format

Messages are sent and received as JSON objects:

```dart
// Incoming events
{
  "type": "game_start",
  "round_id": "round_id",
  "timestamp": "2024-01-01T00:00:00Z"
}

{
  "type": "multiplier_update",
  "round_id": "round_id",
  "current_multiplier": 1.45,
  "timestamp": "2024-01-01T00:00:00.500Z"
}

{
  "type": "game_crash",
  "round_id": "round_id",
  "final_multiplier": 2.45,
  "timestamp": "2024-01-01T00:00:15Z"
}
```

### Reconnection Logic

The WebSocket service includes automatic reconnection with exponential backoff:

- **Initial delay:** 5 seconds
- **Max attempts:** 10
- **Backoff formula:** `delay = initial_delay × attempt_number`

## Data Models

### Snake Case Conversion

The Go backend uses snake_case for JSON fields, while Dart typically uses camelCase. The frontend handles this in several ways:

#### Method 1: Model fromJson with Field Mapping

```dart
class BetModel {
  final String id;
  final String roundId;
  final double amount;
  final double autoCashout;

  factory BetModel.fromJson(Map<String, dynamic> json) {
    return BetModel(
      id: json['id'],
      roundId: json['round_id'],
      amount: json['amount']?.toDouble() ?? 0,
      autoCashout: json['auto_cashout']?.toDouble() ?? 0,
    );
  }
}
```

#### Method 2: JSON Serializable Package (Recommended)

For better maintainability, use the `json_serializable` package with field name mapping:

```dart
@override
Map<String, dynamic> toJson() => {
  'id': id,
  'round_id': roundId,
  'amount': amount,
  'auto_cashout': autoCashout,
};
```

## Service Implementation

### Auth Service

Located in `lib/data/services/auth_api_service.dart`

- `register()` - Register new user
- `login()` - Login user
- `verifyToken()` - Verify token validity
- `healthCheck()` - Check backend health

### Wallet Service

Located in `lib/data/services/wallet_api_service.dart`

- `getWallet()` - Get current wallet balance
- `getTransactions()` - Get transaction history with pagination
- `refreshWallet()` - Refresh wallet balance

### Bet Service

Located in `lib/data/services/bet_api_service.dart`

- `placeBet()` - Place new bet
- `cashout()` - Cashout active bet
- `getBetHistory()` - Get betting history with pagination
- `getGameHistory()` - Get game round history with pagination

### Profile Service

Located in `lib/data/services/profile_api_service.dart`

- `getProfile()` - Get user profile
- `updateProfile()` - Update user profile
- `getStatistics()` - Get user statistics (optional, has fallback)

## Error Handling

### Common Error Codes

| Code | Meaning | Handling |
|------|---------|----------|
| 200 | Success | Process response |
| 400 | Bad Request | Validate input and retry |
| 401 | Unauthorized | Clear token, redirect to login |
| 403 | Forbidden | Show error message |
| 404 | Not Found | Show error message |
| 409 | Conflict | Show error message (e.g., email taken) |
| 500 | Server Error | Show error message, allow retry |
| 503 | Service Unavailable | Show error message, allow retry |

### Authentication Exception

When a 401 error occurs:

```dart
try {
  final wallet = await walletApiService.getWallet();
} on AuthenticationException catch (e) {
  // Automatically handled by the router
  // User is redirected to login
  // Local storage is cleared
}
```

## Development Checklist

- [ ] Backend running on `http://localhost:8080`
- [ ] All `/api/v1` endpoints accessible
- [ ] JWT authentication working
- [ ] WebSocket endpoint `/ws` available
- [ ] CORS configured (if needed)
- [ ] Token expiration time set appropriately
- [ ] Error responses formatted as expected

## Testing the Integration

### Manual Testing Steps

1. **Test Registration:**
   ```
   1. Launch app
   2. Navigate to signup
   3. Enter credentials
   4. Verify token is stored locally
   5. Verify user is redirected to home
   ```

2. **Test Login:**
   ```
   1. Logout from home screen
   2. Enter login credentials
   3. Verify token is stored
   4. Verify navigation to home
   ```

3. **Test Token Expiry:**
   ```
   1. Manually expire the JWT token
   2. Make an API request
   3. Verify automatic redirect to login
   4. Verify local storage is cleared
   ```

4. **Test WebSocket:**
   ```
   1. Navigate to game screen
   2. Verify WebSocket connects
   3. Verify game events are received
   4. Verify multiplier updates are displayed
   ```

5. **Test Betting Flow:**
   ```
   1. Place a bet
   2. Verify bet is sent with correct fields (snake_case)
   3. Verify bet response is parsed correctly
   4. Verify bet appears in history
   5. Test cashout flow
   ```

## Troubleshooting

### 401 Unauthorized on Every Request

**Cause:** Token is invalid or expired
**Solution:**
1. Clear app cache/data
2. Force sign out and sign in again
3. Check backend JWT secret

### WebSocket Connection Failed

**Cause:** WebSocket endpoint not available or connection issue
**Solution:**
1. Verify backend is running
2. Check firewall/network settings
3. Verify `/ws` endpoint exists
4. Check console logs for specific error

### Field Name Mismatch Errors

**Cause:** Model expects different field names than backend sends
**Solution:**
1. Verify backend sends snake_case fields
2. Update model fromJson() methods
3. Use json_serializable package for automatic mapping

### CORS Errors

**Cause:** Cross-Origin Resource Sharing not configured
**Solution:**
1. Configure CORS on backend
2. Add necessary headers if needed
3. Test with same origin first

## Future Enhancements

1. **Token Refresh:** Implement refresh token rotation
2. **Request Caching:** Cache frequent requests
3. **Offline Support:** Handle offline scenarios
4. **Rate Limiting:** Implement client-side rate limiting
5. **Analytics:** Track API performance metrics