# Crash Game - Quick Troubleshooting Guide

## Common Issues & Solutions

### 🔴 RED DOT (WebSocket Disconnected)

**Problem**: Red dot in top-right corner of app

**Causes & Solutions**:

1. **Backend not running**
   ```bash
   # Check if backend is running
   curl http://localhost:8888/health
   
   # If error, start backend
   go run cmd/server/main.go
   ```

2. **Wrong backend URL**
   - Edit `lib/data/services/backend_api_service.dart`
   - Change `baseUrl = 'http://localhost:8888'` to your server URL
   - Edit `lib/data/providers/websocket_provider.dart`
   - Change WebSocket URL accordingly

3. **Firewall blocking**
   - Windows: `netsh advfirewall firewall add rule name="Port 8888" dir=in action=allow protocol=tcp localport=8888`
   - macOS: `sudo pfctl -f /etc/pf.conf`
   - Linux: `sudo ufw allow 8888`

---

### ❌ "Unauthorized" Error

**Problem**: Error message when starting round

**Root Cause**: Missing or invalid user ID header

**Solution**:
- Ensure `X-User-ID` header is being sent
- Update auth middleware in `internal/handlers/game_handler.go`

```dart
// Frontend is auto-generating user ID
final userId = ref.watch(userIdProvider);
print('User ID: $userId');  // Check console logs
```

---

### 💸 "Insufficient Balance" Error

**Problem**: Can't place bet, says insufficient balance

**Causes & Solutions**:

1. **Fresh player needs initialization**
   - Backend auto-creates players with $1000 balance
   - If error persists, check database:
   ```sql
   SELECT * FROM players WHERE id = 'user123';
   ```

2. **Already used all balance**
   - Place smaller bets
   - Create new user by changing `userIdProvider` in code

3. **Database issue**
   - Check backend logs for SQL errors
   - Verify PostgreSQL/SQLite connection

---

### 📡 API Requests Timing Out

**Problem**: "Request timeout" error

**Solutions**:

1. **Backend too slow**
   ```bash
   # Check server status
   curl -v http://localhost:8888/health
   
   # Monitor logs
   tail -f server.log | grep "duration\|latency"
   ```

2. **Network latency**
   - Reduce timeout in API service:
   ```dart
   // Increase timeout in backend_api_service.dart
   .timeout(
     const Duration(seconds: 30),  // from 10
   )
   ```

3. **Database queries slow**
   - Check database is responsive:
   ```bash
   sqlite3 avi.db "SELECT 1;"
   ```

---

### 🎮 Game Doesn't Start / Stuck on "Waiting"

**Problem**: Click "New Round" but nothing happens

**Diagnostic Steps**:

1. **Check WebSocket connection**
   - Should see green dot
   - Check browser console (Chrome DevTools) for WS errors

2. **Check backend round creation**
   ```bash
   curl -X POST http://localhost:8888/api/v1/game/round/start \
     -H "X-User-ID: test"
   ```
   - Should return round data with ID

3. **Check server logs**
   ```bash
   go run cmd/server/main.go 2>&1 | grep -i "error\|round"
   ```

4. **Restart everything**
   ```bash
   # Kill Flutter app
   # Kill backend: Ctrl+C
   # Run backend again
   go run cmd/server/main.go
   # Run Flutter again
   flutter run -d windows
   ```

---

### 💰 Multiplier Not Updating

**Problem**: Multiplier stuck at 1.0x

**Causes & Solutions**:

1. **WebSocket not connected**
   - Check red/green dot
   - See "RED DOT" section above

2. **Not listening to WebSocket**
   - Verify `_listenToMultiplierUpdates()` is called
   - Check logs: `[CrashGame] Bet placed`

3. **Browser DevTools to debug**
   - Open DevTools → Network → WS
   - Should see WebSocket messages every 50ms
   - If nothing, backend not broadcasting

4. **Backend issue**
   ```bash
   # Check backend logs for broadcast
   go run cmd/server/main.go 2>&1 | grep "multiplier_update"
   ```

---

### 🔄 "Bet Already Placed" or Duplicate Bets

**Problem**: Get error that bet is already placed

**Solution**:
1. Check you're not clicking "Place Bet" multiple times
2. Should disable button after first click (button should show loading)
3. If button broken, update `AppButton` widget

```dart
// Button should be disabled while loading
isDisabled: crashGameState.isLoading,
```

---

### 💥 Crash But No Loss / Weird Payout

**Problem**: Game crashed but wrong outcome

**Debug Info Needed**:
1. What multiplier at crash?
2. What was your bet amount?
3. What payout received?

**Check Database**:
```sql
SELECT id, user_id, amount, final_multiplier, payout, status 
FROM game_bets 
ORDER BY created_at DESC LIMIT 5;
```

**Common Issue**: Floating-point rounding
- Our code: `payout = amount * multiplier`
- Example: $100 × 2.5x = $250 (exact)

---

### 🐛 "Game Crashed at" But Still Playing

**Problem**: See crash message but can still place bets

**Causes**:
1. **State out of sync**
   - Restart app
   - Backend and frontend disagreed

2. **Stale WebSocket connection**
   - Will auto-reconnect in 30 seconds
   - Manual fix: Restart app

**Code Fix** (if persistent):
```dart
// In crash_game_api_provider.dart
// Add timeout to restart game after crash
Future.delayed(Duration(seconds: 7), () {
  if (state.hasCrashed) {
    startRound();  // Auto-restart
  }
});
```

---

## Database Issues

### SQLite Locked

```
Error: database is locked
```

**Solution**:
```bash
# Kill any open connections
pkill -f "sqlite3 avi.db"

# Or switch to PostgreSQL for multi-process support
```

### PostgreSQL Connection Failed

```
Error: failed to connect to PostgreSQL
```

**Verify Credentials**:
```bash
# Test connection
psql -h localhost -U postgres -d avi_crash

# If fails, check running
pg_isrunning  # or brew services list
```

### Missing Tables

```sql
-- Create tables manually if migrations fail
CREATE TABLE game_rounds (
  id VARCHAR(255) PRIMARY KEY,
  status VARCHAR(50),
  crash_time_ms INTEGER,
  crash_multiplier FLOAT,
  started_at TIMESTAMP,
  ended_at TIMESTAMP
);

CREATE TABLE game_bets (
  id VARCHAR(255) PRIMARY KEY,
  user_id VARCHAR(255),
  game_round_id VARCHAR(255),
  amount FLOAT,
  status VARCHAR(50),
  payout FLOAT
);

CREATE TABLE players (
  id VARCHAR(255) PRIMARY KEY,
  balance FLOAT,
  total_bet FLOAT,
  total_won FLOAT
);
```

---

## Network Issues

### CORS Error in Browser

```
Access to XMLHttpRequest blocked by CORS
```

**Check CORS Middleware** in `cmd/server/main.go`:
```go
router.Use(corsMiddleware())  // Must be first middleware
```

### WebSocket Upgrade Fails

```
WebSocket upgrade error
```

**Ensure** backend has:
```go
upgrader := websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true  // Allow all origins
    },
}
```

---

## Performance Issues

### Multiplier Updates Lag

**If seeing 5+ second delay**:

1. Check network tab (Chrome DevTools)
   - Should see WS frame every 50ms
   - If not, backend is too slow

2. Reduce load:
   ```bash
   # Restart backend
   go run cmd/server/main.go
   
   # Or reduce UpdateIntervalMs
   # In internal/services/crash_game_service.go
   const UpdateIntervalMs = 100  // from 50
   ```

### High CPU Usage

**If CPU spiking**:
1. Check how many concurrent games
2. Reduce multiplier update frequency
3. Close other apps competing for resources

---

## Emergency Restart

**If everything is broken**:

```bash
# Step 1: Kill all processes
pkill -f "go run cmd/server"
pkill -f "flutter run"

# Step 2: Clear cache/data (optional)
# Windows: Delete "avi.db"
# macOS/Linux: rm avi.db

# Step 3: Restart backend
go run cmd/server/main.go

# Step 4: Restart frontend
flutter run -d windows

# Step 5: Clear database (if really broken)
# Create fresh database:
# Backend will auto-migrate on startup
```

---

## Getting Help

### Check Logs

**Backend Logs**:
```bash
# All logs
go run cmd/server/main.go 2>&1 | tee server.log

# Just errors
go run cmd/server/main.go 2>&1 | grep -i error
```

**Frontend Logs**:
```dart
// Check console output in:
// 1. IDE console (VS Code/Android Studio)
// 2. Chrome DevTools console (if running web)
// 3. Device logs (if mobile)
```

### Useful Debugging Commands

```bash
# Test connectivity
ping localhost
telnet localhost 8888

# Check port usage
netstat -ano | findstr :8888  # Windows
lsof -i :8888                 # macOS/Linux

# Check process
ps aux | grep "go run"

# Test API directly
curl -X POST http://localhost:8888/api/v1/game/round/start \
  -H "X-User-ID: test" \
  -H "Content-Type: application/json" \
  -v

# Monitor real-time
watch curl http://localhost:8888/health
```

### When to Ask for Help

Provide these details:
1. Error message (exact text)
2. Backend logs (last 20 lines)
3. Frontend console logs
4. What you were doing when error occurred
5. System info (Windows/macOS/Linux)
6. Backend running? Frontend running?

---

## Useful Documentation

- [Full Deployment Guide](CRASH_GAME_FULL_DEPLOYMENT_GUIDE.md)
- [Backend Integration Guide](CRASH_GAME_BACKEND_INTEGRATION.md)  
- [Frontend Guide](CRASH_GAME_FRONTEND_GUIDE.md)
- [Developer Quick Reference](CRASH_GAME_DEVELOPER_QUICK_REFERENCE.md)
