# Backend API Specification Document

**Project:** Aviator Betting Game  
**Backend:** Go Backend  
**Base URL:** `http://localhost:8080`  
**API Version:** `/api/v1`  
**WebSocket URL:** `ws://localhost:8080/ws`  

---

## Table of Contents

1. [API Endpoints Summary](#api-endpoints-summary)
2. [Configuration](#configuration)
3. [Authentication](#authentication)
4. [Data Types](#data-types)
5. [Error Responses](#error-responses)
6. [Endpoints](#endpoints)
7. [WebSocket Events](#websocket-events)

---

## API Endpoints Summary

### Quick Reference - All Endpoints with HTTP Methods

| # | HTTP Method | Endpoint | Description | Auth Required | Status |
|---|---|---|---|---|---|
| **Authentication** | | | | | |
| 1 | `POST` | `/api/v1/register` | User registration | No | 201/400/409 |
| 2 | `POST` | `/api/v1/login` | User login | No | 200/400/401 |
| 3 | `GET` | `/api/v1/verify` | Verify JWT token | Yes | 200/401 |
| 4 | `GET` | `/api/v1/health` | Health check | No | 200/503 |
| **Profile Management** | | | | | |
| 5 | `GET` | `/api/v1/profile` | Get user profile | Yes | 200/401/404 |
| 6 | `PUT` | `/api/v1/profile` | Update user profile | Yes | 200/400/401/409 |
| 7 | `GET` | `/api/v1/profile/statistics` | Get user statistics | Yes | 200/401/404 |
| **Wallet Management** | | | | | |
| 8 | `GET` | `/api/v1/wallet` | Get wallet balance | Yes | 200/401/404 |
| 9 | `GET` | `/api/v1/transactions/history` | Get transaction history | Yes | 200/401 |
| **Betting** | | | | | |
| 10 | `POST` | `/api/v1/bet` | Place a bet | Yes | 201/400/401/422 |
| 11 | `POST` | `/api/v1/cashout` | Cash out a bet | Yes | 200/400/401/404/422 |
| 12 | `GET` | `/api/v1/bets/history` | Get bet history | Yes | 200/401 |
| 13 | `GET` | `/api/v1/game/history` | Get game history | Yes | 200/401 |

---

## Configuration

### Base Settings
```
Base URL: http://localhost:8080
API Prefix: /api/v1
Content-Type: application/json
Authorization Header: Bearer {token}
Field Naming: snake_case (JSON), camelCase (Dart)
```

### Timeouts
```
Connection Timeout: 30 seconds
Request Timeout: 30 seconds
WebSocket Timeout: None (persistent)
```

---

## Authentication

### JWT Token
**Type:** String  
**Format:** JWT Bearer Token  
**Storage:** LocalStorage (SharedPreferences)  
**Expiry:** Backend-dependent (typically 24-48 hours)  
**Refresh:** Not implemented (full re-login required)  

### Authorization Header
```
Authorization: Bearer {jwt_token}
```

### Token Errors
- **401 Unauthorized:** Token invalid, expired, or missing
- **403 Forbidden:** User lacks permissions

---

## Data Types

### Primitive Types

| Type | Example | Size | Notes |
|------|---------|------|-------|
| `string` | "john@example.com" | Variable | UTF-8 encoded |
| `int` | 1000 | 32-64 bits | Signed integer |
| `double` | 1000.50 | 64 bits | IEEE 754 floating point |
| `boolean` | true/false | 1 bit | true or false |
| `timestamp` | "2024-01-01T00:00:00Z" | Variable | ISO 8601 format |
| `uuid` | "550e8400-e29b-41d4-a716-446655440000" | 36 chars | UUID v4 format |

### Standard Response Format

```json
{
  "status": "success|error",
  "data": {},
  "error": {
    "code": 400,
    "message": "error message"
  },
  "timestamp": "2024-01-01T00:00:00Z"
}
```

### Data Models

#### User Model
```json
{
  "id": "string(uuid)",
  "name": "string(1-100)",
  "email": "string(email)",
  "balance": "double(≥0)",
  "created_at": "timestamp",
  "updated_at": "timestamp"
}
```

#### Wallet Model
```json
{
  "id": "string(uuid)",
  "user_id": "string(uuid)",
  "balance": "double(≥0)",
  "currency": "string(3)",
  "total_winnings": "double(≥0)",
  "total_losses": "double(≥0)",
  "last_updated": "timestamp"
}
```

#### Bet Model
```json
{
  "id": "string(uuid)",
  "user_id": "string(uuid)",
  "round_id": "string(uuid)",
  "amount": "double(>0)",
  "auto_cashout": "double(≥1.0)",
  "cashout_multiplier": "double|null",
  "final_multiplier": "double|null",
  "status": "enum(active|won|lost|cashed_out|failed)",
  "placed_at": "timestamp",
  "ended_at": "timestamp|null",
  "winnings": "double|null"
}
```

#### Game Round Model
```json
{
  "id": "string(uuid)",
  "status": "enum(waiting|running|crashed)",
  "current_multiplier": "double(≥1.0)",
  "final_multiplier": "double|null",
  "crashed_at": "double|null",
  "countdown_seconds": "int(≥0)",
  "started_at": "timestamp|null",
  "ended_at": "timestamp|null",
  "created_at": "timestamp"
}
```

#### Transaction Model
```json
{
  "id": "string(uuid)",
  "user_id": "string(uuid)",
  "type": "enum(bet|cashout|win|withdrawal|deposit|loss)",
  "amount": "double(>0)",
  "balance_before": "double(≥0)",
  "balance_after": "double(≥0)",
  "reference": "string(uuid)",
  "description": "string(1-500)",
  "status": "enum(completed|pending|failed)",
  "timestamp": "timestamp"
}
```

---

## Error Responses

### Error Response Format
```json
{
  "status": "error",
  "error": {
    "code": "int",
    "message": "string",
    "field": "string|null",
    "validation_errors": [
      {
        "field": "string",
        "message": "string"
      }
    ]
  },
  "timestamp": "timestamp"
}
```

### HTTP Status Codes

| Code | Message | Cause | Recovery |
|------|---------|-------|----------|
| 200 | OK | Successful request | None |
| 201 | Created | Resource created | None |
| 400 | Bad Request | Invalid input | Fix input and retry |
| 401 | Unauthorized | Missing/invalid token | Re-authenticate |
| 403 | Forbidden | Insufficient permissions | Use appropriate account |
| 404 | Not Found | Resource doesn't exist | Check resource ID |
| 409 | Conflict | Resource conflict (e.g., email exists) | Use different value |
| 422 | Unprocessable Entity | Validation failed | Fix validation errors |
| 429 | Too Many Requests | Rate limited | Wait and retry |
| 500 | Internal Server Error | Server error | Retry later |
| 503 | Service Unavailable | Server down | Wait and retry |

### Common Error Codes

| Error Code | HTTP Code | Message | Recovery |
|-----------|-----------|---------|----------|
| 1001 | 401 | Invalid credentials | Check email/password |
| 1002 | 401 | Token expired | Re-login |
| 1003 | 401 | Token invalid | Re-login |
| 2001 | 409 | Email already exists | Use different email |
| 2002 | 404 | User not found | Check user ID |
| 3001 | 400 | Insufficient balance | Add funds |
| 3002 | 404 | Bet not found | Check bet ID |
| 3003 | 400 | Bet already closed | Already processed |
| 4001 | 404 | Round not found | Check round ID |
| 5001 | 500 | Database error | Retry or contact support |

---

## Endpoints

### 1. Authentication Endpoints

#### 1.1 Register
**Endpoint:** `POST /api/v1/register`

**Request:**
```json
{
  "name": "string(1-100)[required]",
  "email": "string(email)[required]",
  "password": "string(8-255)[required]"
}
```

**Response (201):**
```json
{
  "token": "string(jwt)[required]",
  "user": {
    "id": "string(uuid)[required]",
    "name": "string[required]",
    "email": "string(email)[required]",
    "balance": "double[required]",
    "created_at": "timestamp[required]"
  }
}
```

**Errors:** 400, 409

**Status Codes:**
- 201: User created successfully
- 400: Invalid input (name, email, password format)
- 409: Email already exists

---

#### 1.2 Login
**Endpoint:** `POST /api/v1/login`

**Request:**
```json
{
  "email": "string(email)[required]",
  "password": "string[required]"
}
```

**Response (200):**
```json
{
  "token": "string(jwt)[required]",
  "user": {
    "id": "string(uuid)[required]",
    "name": "string[required]",
    "email": "string(email)[required]",
    "balance": "double[required]",
    "created_at": "timestamp[required]"
  }
}
```

**Errors:** 400, 401

**Status Codes:**
- 200: Login successful
- 400: Invalid input format
- 401: Invalid credentials

---

#### 1.3 Verify Token
**Endpoint:** `GET /api/v1/verify`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "id": "string(uuid)[required]",
  "name": "string[required]",
  "email": "string(email)[required]",
  "balance": "double[required]",
  "created_at": "timestamp[required]"
}
```

**Errors:** 401

**Status Codes:**
- 200: Token valid
- 401: Token invalid or expired

---

#### 1.4 Health Check
**Endpoint:** `GET /api/v1/health`

**Response (200):**
```json
{
  "status": "string(healthy|degraded|unhealthy)[required]",
  "timestamp": "timestamp[required]",
  "database": "string(connected|disconnected)[required]"
}
```

**Status Codes:**
- 200: Server healthy
- 503: Server unhealthy

---

### 2. Profile Endpoints

#### 2.1 Get Profile
**Endpoint:** `GET /api/v1/profile`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "id": "string(uuid)[required]",
  "name": "string[required]",
  "email": "string(email)[required]",
  "balance": "double[required]",
  "total_bets": "int[required]",
  "total_wins": "int[required]",
  "win_rate": "double[required]",
  "created_at": "timestamp[required]",
  "updated_at": "timestamp[required]"
}
```

**Errors:** 401, 404

**Status Codes:**
- 200: Profile retrieved
- 401: Unauthorized
- 404: User not found

---

#### 2.2 Update Profile
**Endpoint:** `PUT /api/v1/profile`

**Request Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request:**
```json
{
  "name": "string(1-100)[optional]",
  "email": "string(email)[optional]"
}
```

**Response (200):**
```json
{
  "id": "string(uuid)[required]",
  "name": "string[required]",
  "email": "string(email)[required]",
  "balance": "double[required]",
  "updated_at": "timestamp[required]"
}
```

**Errors:** 400, 401, 409

**Status Codes:**
- 200: Profile updated
- 400: Invalid input
- 401: Unauthorized
- 409: Email already taken

---

#### 2.3 Get Statistics
**Endpoint:** `GET /api/v1/profile/statistics`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "total_bets": "int[required]",
  "total_wins": "int[required]",
  "total_losses": "int[required]",
  "total_wagered": "double[required]",
  "total_winnings": "double[required]",
  "average_multiplier": "double[required]",
  "win_rate": "double[required]",
  "highest_multiplier": "double[required]",
  "largest_win": "double[required]",
  "largest_loss": "double[required]"
}
```

**Errors:** 401, 404

**Status Codes:**
- 200: Statistics retrieved
- 401: Unauthorized
- 404: Optional endpoint (may not exist)

---

### 3. Wallet Endpoints

#### 3.1 Get Wallet
**Endpoint:** `GET /api/v1/wallet`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "id": "string(uuid)[required]",
  "user_id": "string(uuid)[required]",
  "balance": "double(≥0)[required]",
  "currency": "string(3)[required]",
  "last_updated": "timestamp[required]"
}
```

**Errors:** 401, 404

**Status Codes:**
- 200: Wallet retrieved
- 401: Unauthorized
- 404: Wallet not found

---

#### 3.2 Get Transactions History
**Endpoint:** `GET /api/v1/transactions/history`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Query Parameters:**
```
page: int(≥1)[optional, default=1]
limit: int(1-100)[optional, default=10]
type: enum(bet|cashout|win|withdrawal|deposit|loss)[optional]
```

**Response (200):**
```json
{
  "transactions": [
    {
      "id": "string(uuid)[required]",
      "user_id": "string(uuid)[required]",
      "type": "string(enum)[required]",
      "amount": "double[required]",
      "balance_before": "double[required]",
      "balance_after": "double[required]",
      "reference": "string(uuid)[required]",
      "description": "string[required]",
      "status": "string(enum)[required]",
      "timestamp": "timestamp[required]"
    }
  ],
  "pagination": {
    "total": "int[required]",
    "page": "int[required]",
    "limit": "int[required]",
    "pages": "int[required]"
  }
}
```

**Errors:** 401

**Status Codes:**
- 200: Transactions retrieved
- 401: Unauthorized

---

### 4. Betting Endpoints

#### 4.1 Place Bet
**Endpoint:** `POST /api/v1/bet`

**Request Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request:**
```json
{
  "round_id": "string(uuid)[required]",
  "amount": "double(>0)[required]",
  "auto_cashout": "double(≥1.0)[required]"
}
```

**Response (201):**
```json
{
  "id": "string(uuid)[required]",
  "user_id": "string(uuid)[required]",
  "round_id": "string(uuid)[required]",
  "amount": "double[required]",
  "auto_cashout": "double[required]",
  "status": "string(enum)[required]",
  "placed_at": "timestamp[required]"
}
```

**Errors:** 400, 401, 422

**Status Codes:**
- 201: Bet placed successfully
- 400: Invalid input or insufficient balance
- 401: Unauthorized
- 422: Validation failed (amount too high/low, round not found)

---

#### 4.2 Cashout Bet
**Endpoint:** `POST /api/v1/cashout`

**Request Headers:**
```
Authorization: Bearer {token}
Content-Type: application/json
```

**Request:**
```json
{
  "bet_id": "string(uuid)[required]",
  "current_multiplier": "double(≥1.0)[required]"
}
```

**Response (200):**
```json
{
  "id": "string(uuid)[required]",
  "user_id": "string(uuid)[required]",
  "status": "string(enum)[required]",
  "cashout_multiplier": "double[required]",
  "winnings": "double[required]",
  "cashed_out_at": "timestamp[required]"
}
```

**Errors:** 400, 401, 404, 422

**Status Codes:**
- 200: Cashout successful
- 400: Invalid multiplier
- 401: Unauthorized
- 404: Bet not found
- 422: Bet already closed

---

#### 4.3 Get Bet History
**Endpoint:** `GET /api/v1/bets/history`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Query Parameters:**
```
page: int(≥1)[optional, default=1]
limit: int(1-100)[optional, default=20]
status: enum(won|lost|cashed_out|failed)[optional]
```

**Response (200):**
```json
{
  "bets": [
    {
      "id": "string(uuid)[required]",
      "round_id": "string(uuid)[required]",
      "amount": "double[required]",
      "status": "string(enum)[required]",
      "final_multiplier": "double|null",
      "winnings": "double|null",
      "placed_at": "timestamp[required]",
      "ended_at": "timestamp|null"
    }
  ],
  "pagination": {
    "total": "int[required]",
    "page": "int[required]",
    "limit": "int[required]",
    "pages": "int[required]"
  }
}
```

**Errors:** 401

**Status Codes:**
- 200: Bet history retrieved
- 401: Unauthorized

---

#### 4.4 Get Game History
**Endpoint:** `GET /api/v1/game/history`

**Request Headers:**
```
Authorization: Bearer {token}
```

**Query Parameters:**
```
page: int(≥1)[optional, default=1]
limit: int(1-100)[optional, default=50]
```

**Response (200):**
```json
{
  "rounds": [
    {
      "id": "string(uuid)[required]",
      "final_multiplier": "double[required]",
      "crashed_at": "double[required]",
      "started_at": "timestamp[required]",
      "ended_at": "timestamp[required]",
      "players_count": "int[required]"
    }
  ],
  "pagination": {
    "total": "int[required]",
    "page": "int[required]",
    "limit": "int[required]",
    "pages": "int[required]"
  }
}
```

**Errors:** 401

**Status Codes:**
- 200: Game history retrieved
- 401: Unauthorized

---

## WebSocket Events

### WebSocket URL
```
ws://localhost:8080/ws
```

### Connection
**Initial Message (Client → Server):**
```json
{
  "type": "auth",
  "token": "string(jwt)"
}
```

### Event Types

#### Game Start
**Direction:** Server → Client  
**Trigger:** New game round begins

```json
{
  "type": "game_start",
  "round_id": "string(uuid)",
  "timestamp": "timestamp"
}
```

#### Multiplier Update
**Direction:** Server → Client  
**Trigger:** ~100ms during game (or on significant changes)

```json
{
  "type": "multiplier_update",
  "round_id": "string(uuid)",
  "current_multiplier": "double(≥1.0)",
  "timestamp": "timestamp"
}
```

#### Game Crash
**Direction:** Server → Client  
**Trigger:** Game ends/crashes

```json
{
  "type": "game_crash",
  "round_id": "string(uuid)",
  "final_multiplier": "double(≥1.0)",
  "timestamp": "timestamp"
}
```

#### Bet Placed
**Direction:** Server → Client  
**Trigger:** User or another user places bet

```json
{
  "type": "bet_placed",
  "round_id": "string(uuid)",
  "amount": "double",
  "timestamp": "timestamp"
}
```

#### Bet Cashed Out
**Direction:** Server → Client  
**Trigger:** User cashes out

```json
{
  "type": "bet_cashed_out",
  "round_id": "string(uuid)",
  "multiplier": "double",
  "winnings": "double",
  "timestamp": "timestamp"
}
```

#### Error
**Direction:** Server → Client

```json
{
  "type": "error",
  "message": "string",
  "code": "int",
  "timestamp": "timestamp"
}
```

### Message Sending (Client → Server)

#### Place Bet
```json
{
  "type": "place_bet",
  "round_id": "string(uuid)",
  "amount": "double",
  "auto_cashout": "double"
}
```

#### Manual Cashout
```json
{
  "type": "cashout",
  "bet_id": "string(uuid)",
  "current_multiplier": "double"
}
```

#### Ping
```json
{
  "type": "ping"
}
```

#### Pong (Response to Ping)
```json
{
  "type": "pong"
}
```

---

## Request/Response Examples

### Complete Examples

#### Register User
```bash
POST http://localhost:8080/api/v1/register
Content-Type: application/json

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

Response (201):
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "John Doe",
    "email": "john@example.com",
    "balance": 0,
    "created_at": "2024-01-01T00:00:00Z"
  }
}
```

#### Place Bet
```bash
POST http://localhost:8080/api/v1/bet
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json

{
  "round_id": "660e8400-e29b-41d4-a716-446655440001",
  "amount": 50.00,
  "auto_cashout": 2.5
}

Response (201):
{
  "id": "770e8400-e29b-41d4-a716-446655440002",
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "round_id": "660e8400-e29b-41d4-a716-446655440001",
  "amount": 50.00,
  "auto_cashout": 2.5,
  "status": "active",
  "placed_at": "2024-01-01T00:00:00Z"
}
```

#### Get Wallet
```bash
GET http://localhost:8080/api/v1/wallet
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Response (200):
{
  "id": "880e8400-e29b-41d4-a716-446655440003",
  "user_id": "550e8400-e29b-41d4-a716-446655440000",
  "balance": 2250.50,
  "currency": "USD",
  "last_updated": "2024-01-01T00:15:30Z"
}
```

---

## Implementation Notes

### Field Validation Rules

#### String Fields
- **email:** Must be valid email format (RFC 5322)
- **password:** Min 8 chars, must contain uppercase, lowercase, number, special char
- **name:** 1-100 characters, alphanumeric + spaces
- **uuid:** Must be valid UUID v4 format

#### Numeric Fields
- **amount:** Must be positive (>0), max 2 decimal places
- **multiplier:** Must be ≥1.0, typically ≤100.0
- **balance:** Must be ≥0, max 2 decimal places

#### Enum Fields
- **status (bet):** active, won, lost, cashed_out, failed
- **status (transaction):** completed, pending, failed
- **type (transaction):** bet, cashout, win, withdrawal, deposit, loss
- **status (game):** waiting, running, crashed

### Rate Limiting
- **Per IP:** 1000 requests/hour
- **Per User:** 500 requests/hour
- **WebSocket:** Unlimited (server-side limits apply)
- **Response Header:** `X-RateLimit-Remaining: {count}`

### Pagination
- **Default Limit:** 10-20 items per page
- **Max Limit:** 100 items per page
- **Min Page:** 1
- **Total Pages:** Calculated as `ceil(total / limit)`

### Timestamps
- **Format:** ISO 8601 (YYYY-MM-DDTHH:MM:SSZ)
- **Timezone:** UTC (Z suffix)
- **Precision:** Seconds

---

## Code Generation Checklist

- [ ] Base API client with error handling
- [ ] Authentication service (login, register, verify)
- [ ] Profile service (get, update, statistics)
- [ ] Wallet service (get wallet, transactions history)
- [ ] Betting service (place bet, cashout, histories)
- [ ] Model generation for all data types
- [ ] Error handling for all HTTP codes
- [ ] WebSocket client with event handling
- [ ] Automatic token injection in headers
- [ ] Request/response logging
- [ ] Retry logic with exponential backoff
- [ ] Cache management for responses
- [ ] Unit tests for all endpoints