# Flutter + Go Backend Integration Guide

## Quick Setup

### Step 1: Start Go Backend

```powershell
cd "D:\go project\avi_bd"
go run cmd/server/main.go
```

**Expected Output:**
```
2026/04/08 10:00:00 Database connection initialized
2026/04/08 10:00:00 Server running on http://localhost:8080
```

**Verify Backend is Running:**
```powershell
curl http://localhost:8080/api/v1/health
```

Should return:
```json
{
  "status": "healthy",
  "timestamp": "2026-04-08T10:00:00Z",
  "database": "connected"
}
```

---

### Step 2: Run Flutter App

#### Option A: Run from VS Code
1. Open the Flutter project in VS Code: `d:\flutter project\avi`
2. Run > Start Debugging (F5)
3. Or press `F5` directly

#### Option B: Run from Terminal

```powershell
cd "d:\flutter project\avi"

# Get dependencies
flutter pub get

# Run the app
flutter run

# Or run on web (if needed)
flutter run -d chrome

# Or run on specific device
flutter run -d <device_id>
```

#### Option C: Run on Android Emulator

```powershell
# List available devices
flutter devices

# Run on specific device
flutter run -d emulator-5554
```

---

## Testing Login Flow

### Test 1: Register New User

**In Flutter App:**
1. Tap "Sign up" on login screen
2. Enter:
   - Email: `test@example.com`
   - Password: `password123`
   - Name: `Test User`
3. Tap "Create Account"

**Expected:**
- Auto-login and redirect to home
- User data saved locally

**In Logs (Debug Console):**
```
[AuthApiService] Registering user: test@example.com
[AuthApiService] Register response type: _InternalLinkedHashMap<String, dynamic>
[AuthApiService] Register response: {token: eyJ..., user: {id:..., name:..., email:...}}
[AuthRepository] Register response: {token: eyJ..., user: {id:..., name:..., email:...}}
```

### Test 2: Login with Registered User

**In Flutter App:**
1. Stay on login screen
2. Enter:
   - Email: `test@example.com`
   - Password: `password123`
3. Tap "Login"

**Expected:**
- Redirect to home screen
- No errors

**In Logs:**
```
[ApiService] POST request to: /api/v1/login
[ApiService] POST response status: 200
[AuthApiService] Logging in user: test@example.com
[AuthApiService] Login response: {token: eyJ..., user: {...}}
[AuthRepository] Login response: {token: eyJ..., user: {...}}
```

### Test 3: Invalid Credentials

**In Flutter App:**
1. Enter wrong password
2. Tap "Login"

**Expected:**
- Show error: "Invalid credentials"
- Stay on login screen

**In Logs:**
```
[ApiService] POST response status: 401
[AuthApiService] Login error: Invalid credentials
[AuthRepository] Login error: Invalid credentials
```

---

## Troubleshooting Guide

### Error: "Connection refused"

**Cause:** Backend not running

**Solution:**
```powershell
# Check if backend is running
Get-Process -Name "go" | Select-Object Id, ProcessName

# If not running, start it
cd "D:\go project\avi_bd"
go run cmd/server/main.go
```

---

### Error: "Invalid login response"

**Cause:** Response structure mismatch

**Solution:** Check logs for:
```
[ApiService] POST response data: {...}
```

Should contain:
```json
{
  "token": "jwt_token_here",
  "user": {
    "id": "...",
    "name": "...",
    "email": "...",
    "balance": 100.0,
    "created_at": "2026-04-08T..."
  }
}
```

---

### Error: "Connection timeout"

**Cause:** Backend running but slow response

**Solution:**
```powershell
# Increase timeout in api_constants.dart
static const Duration connectTimeout = Duration(seconds: 60);
static const Duration receiveTimeout = Duration(seconds: 60);
```

---

### Error: "Invalid email format"

**Cause:** Backend validation

**Solution:** Make sure email is valid format (user@domain.com)

---

### Error: "Email already registered"

**Cause:** Email already exists in database

**Solution:** Use different email or clear database:
```powershell
# Connect to PostgreSQL
psql -U postgres

# In psql:
DROP DATABASE aviator_db;
CREATE DATABASE aviator_db;
\q
```

Then restart backend:
```powershell
cd "D:\go project\avi_bd"
go run cmd/server/main.go
```

---

## Debugging Tips

### Enable Full Logging

Add this to main.dart:
```dart
void main() {
  // Enable Dio logging
  if (kDebugMode) {
    Dio().interceptors.add(LoggingInterceptor());
  }
  runApp(const MyApp());
}

class LoggingInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    print('REQUEST[${options.method}] => PATH: ${options.path}');
    print('BODY: ${options.data}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    print('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
    print('BODY: ${response.data}');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
    print('ERROR: ${err.error}');
    super.onError(err, handler);
  }
}
```

---

### Check Flutter Doctor

```powershell
flutter doctor -v
```

Should show:
```
[✓] Flutter (version 3.x.x)
[✓] Android toolchain
[✓] Dart (version 3.x.x)
[✓] Chrome
```

---

### Check with curl (Backend Testing)

```powershell
# Test registration
$body = @{
    name = "Test User"
    email = "test@example.com"
    password = "password123"
} | ConvertTo-Json

Invoke-WebRequest -Uri http://localhost:8080/api/v1/register `
    -Method POST `
    -Headers @{"Content-Type"="application/json"} `
    -Body $body

# Test login
$loginBody = @{
    email = "test@example.com"
    password = "password123"
} | ConvertTo-Json

Invoke-WebRequest -Uri http://localhost:8080/api/v1/login `
    -Method POST `
    -Headers @{"Content-Type"="application/json"} `
    -Body $loginBody
```

---

## API Endpoints Reference

| Method | Endpoint | Status | Protected |
|--------|----------|--------|-----------|
| POST | /api/v1/register | 201 ✅ | No |
| POST | /api/v1/login | 200 ✅ | No |
| GET | /api/v1/health | 200 ✅ | No |
| GET | /api/v1/verify | 200 ✅ | Yes |
| GET | /api/v1/profile | 200 ✅ | Yes |
| PUT | /api/v1/profile | 200 ✅ | Yes |
| GET | /api/v1/wallet | 200 ✅ | Yes |
| POST | /api/v1/bet | 201 ✅ | Yes |
| POST | /api/v1/cashout | 200 ✅ | Yes |
| GET | /api/v1/bets/history | 200 ✅ | Yes |
| GET | /ws | 101 ✅ | No |

---

## Key Configuration Files

### Flutter:
- **API Base URL:** [lib/core/constants/api_constants.dart](lib/core/constants/api_constants.dart)
  ```dart
  static const String baseUrl = 'http://localhost:8080';
  ```

### Go Backend:
- **Config:** `D:\go project\avi_bd\.env`
- **Routes:** `D:\go project\avi_bd\internal\routes\routes.go`
- **Database:** PostgreSQL on `localhost:5432`

---

## What's Been Fixed

✅ **UserModel** - Now supports `balance` field from backend  
✅ **Login/Register** - Better error handling and validation  
✅ **Type Checking** - Proper type casting for responses  
✅ **Logging** - Debug prints to track requests/responses  
✅ **Error Messages** - Clear error messages from backend  

---

## Next Steps

1. ✅ Start backend
2. ✅ Run Flutter app
3. ✅ Test signup flow
4. ✅ Test login flow
5. 📝 Test other features (wallet, bets, etc.)

---

**Last Updated:** April 8, 2026  
**Status:** Ready for testing
