> ## Documentation Index
> Fetch the complete documentation index at: https://docs-ts.playservices.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Player Management

> Register players, handle rebuys, manage sessions, and track participation in tournaments

# Player Management

The Player Management APIs enable casino operators to register players for tournaments, handle rebuys, manage player sessions, and track tournament participation.

## Player Registration

### Register Player for Tournament

Register a player for a specific tournament:

```http theme={null}
POST /api/tournaments/12345/players
Authorization: Bearer {your-api-key}
Content-Type: application/json

{
  "user_id": "USER_12345",
  "display_name": "TestPlayer",
  "entry_payment_details": {
    "payment_id": "PAY_67890"
  }
}
```

**Response:**

```json theme={null}
{
  "player_id": "456",
  "internal_player_id": "TP_12345_456_789",
  "tournament_id": "12345",
  "status": "registered",
  "crash-classic": {
    "jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "game_url": "https://games.casino.com/crash?jwt=eyJ0eXAi..."
  },
  "message": "Player registered successfully"
}
```

### JWT Token & Game Access

<Info>
  The JWT token contains tournament and player information needed for game platform authentication. Tokens are valid for the duration of the tournament.
</Info>

**Game Access Structure:**
Game access information is keyed by the game slug (e.g., `crash-classic`). Each game object contains:

```json theme={null}
{
  "crash-classic": {
    "jwt": "eyJ0eXAi...",
    "game_url": "https://games.casino.com/crash?jwt=eyJ0eXAi..."
  }
}
```

**Usage:**

* **Game Key**: Object key matches the tournament's game slug
* **jwt**: Token for game platform authentication
* **game\_url**: Direct link to launch the tournament game (includes JWT as query parameter)

**JWT Payload Structure:**

```json theme={null}
{
  "tournament_id": "12345",
  "internal_player_id": "TP_12345_456_789",
  "external_user_id": "USER_12345",
  "display_name": "TestPlayer",
  "operator_id": "op_123",
  "iat": 1642086000,
  "exp": 1642089600
}
```

## Player Rebuy System

### Process Player Rebuy

Handle additional entries for players during tournament:

```http theme={null}
POST /api/tournaments/12345/players/456/rebuy
Authorization: Bearer {your-api-key}
Content-Type: application/json

{
  "additional_entries": 1
}
```

**Response:**

```json theme={null}
{
  "rebuy_approved": true,
  "new_entry_count": 2,
  "total_paid": 30,
  "additional_entries": 1,
  "entry_statistics": {
    "total_players": 25,
    "total_entries": 48,
    "average_entries_per_player": 1.92
  },
  "message": "Rebuy processed successfully"
}
```

### Rebuy Validation

<Warning>
  Rebuys are subject to tournament configuration limits and timing restrictions. The API will validate all rebuy attempts.
</Warning>

**Rebuy Conditions:**

* Tournament allows rebuys (`rebuy_enabled: true`)
* Player hasn't reached maximum entries (`max_entries_per_player`)
* Tournament is in valid status for rebuys (`in_progress`)
* Player has sufficient balance for rebuy fee

**Multiple Entry System:**
Players can purchase additional tournament entries up to the configured limit. Each entry acts as a separate "life" or chance in the tournament.

**Rebuy Fee Calculation:**

* First entry: Entry fee (e.g., \$10)
* Additional entries: Rebuy fee (e.g., \$20 each)
* Total for 3 entries: $10 + $20 + $20 = $50

### Advanced Rebuy Scenarios

<Tabs>
  <Tab title="Multiple Entries">
    **Request multiple entries at once:**

    ```json theme={null}
    {
      "additional_entries": 2
    }
    ```

    **Response includes updated statistics:**

    ```json theme={null}
    {
      "rebuy_approved": true,
      "new_entry_count": 3,
      "total_paid": 50,
      "additional_entries": 2,
      "entry_statistics": {
        "total_players": 25,
        "total_entries": 52,
        "average_entries_per_player": 2.08
      }
    }
    ```
  </Tab>

  <Tab title="Default Behavior">
    **No additional\_entries specified defaults to 1:**

    ```json theme={null}
    {}
    ```

    **Equivalent to:**

    ```json theme={null}
    {
      "additional_entries": 1
    }
    ```
  </Tab>

  <Tab title="Validation Errors">
    **Exceeding maximum entries:**

    ```json theme={null}
    {
      "error": "Would exceed maximum entries per player",
      "current_entries": 2,
      "max_entries": 2,
      "additional_requested": 1
    }
    ```

    **Tournament not allowing rebuys:**

    ```json theme={null}
    {
      "error": "Rebuys are not enabled for this tournament"
    }
    ```

    **Invalid tournament status:**

    ```json theme={null}
    {
      "error": "Rebuys are not allowed in current tournament status"
    }
    ```
  </Tab>
</Tabs>

## Player Session Management

### Get Tournament Players

Retrieve list of players registered for a tournament:

```http theme={null}
GET /api/tournaments/12345/players?status=active&limit=50
Authorization: Bearer {your-api-key}
```

**Response:**

```json theme={null}
{
  "players": [
    {
      "playerId": "tp_player_456",
      "userId": "player_123", 
      "displayName": "PlayerName",
      "status": "active",
      "entryCount": 2,
      "totalPaid": 20.00,
      "currentPosition": 15,
      "points": 1250,
      "registeredAt": "2024-01-15T19:30:00Z"
    }
  ],
  "pagination": {
    "total": 87,
    "limit": 50,
    "offset": 0
  }
}
```

### Player Status Values

| Status       | Description                               | Available Actions  |
| ------------ | ----------------------------------------- | ------------------ |
| `registered` | Player registered, tournament not started | Remove, Update     |
| `active`     | Player participating in tournament        | Rebuy, View Status |
| `advancing`  | Player advanced to next round             | View Status        |
| `eliminated` | Player eliminated from tournament         | View Final Results |
| `withdrawn`  | Player left tournament voluntarily        | View Final Results |

### Remove Player

Remove a player from tournament (before tournament starts):

```http theme={null}
DELETE /api/tournaments/12345/players/tp_player_456
Authorization: Bearer {your-api-key}
Content-Type: application/json

{
  "reason": "player_request",
  "processRefund": true
}
```

**Response:**

```json theme={null}
{
  "playerId": "tp_player_456",
  "removed": true,
  "refundProcessed": true,
  "refundAmount": 20.00,
  "reason": "player_request"
}
```

## Player Data & Statistics

### Get Player Details

Retrieve detailed information about a specific player in a tournament:

```http theme={null}
GET /api/tournaments/12345/players/tp_player_456
Authorization: Bearer {your-api-key}
```

**Response:**

```json theme={null}
{
  "playerId": "tp_player_456",
  "userId": "player_123",
  "displayName": "PlayerName",
  "status": "active",
  "registeredAt": "2024-01-15T19:30:00Z",
  "entryCount": 2,
  "totalPaid": 20.00,
  "currentStats": {
    "position": 15,
    "points": 1250,
    "currentRound": 3,
    "gamesPlayed": 8,
    "averageScore": 156.25
  },
  "sessionInfo": {
    "lastActiveAt": "2024-01-15T20:30:00Z",
    "connectionStatus": "connected",
    "gameRoomId": "room_abc123"
  }
}
```

## Error Handling

### Common Player Management Errors

#### Duplicate Registration

```json theme={null}
{
  "error": "player_already_registered",
  "message": "Player is already registered for this tournament",
  "playerId": "tp_player_456",
  "tournamentId": "12345"
}
```

#### Rebuy Limit Exceeded

```json theme={null}
{
  "error": "rebuy_limit_exceeded",
  "message": "Player has reached maximum entries limit",
  "currentEntries": 3,
  "maxEntries": 3
}
```

#### Tournament Full

```json theme={null}
{
  "error": "tournament_full",
  "message": "Tournament has reached maximum player capacity",
  "currentPlayers": 100,
  "maxPlayers": 100
}
```

## Integration Examples

### Player Registration Flow

```javascript theme={null}
// Register player for tournament
const registerPlayer = async (tournamentId, playerData) => {
  try {
    const response = await fetch(`/api/tournaments/${tournamentId}/players`, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer your-api-key',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(playerData)
    });
    
    if (!response.ok) {
      throw new Error(`Registration failed: ${response.status}`);
    }
    
    const registration = await response.json();
    
    // Redirect player to game with JWT token
    window.location.href = registration.gameUrl;
    
    return registration;
  } catch (error) {
    console.error('Player registration failed:', error);
    throw error;
  }
};
```

### Rebuy Processing

```javascript theme={null}
// Process player rebuy
const processRebuy = async (tournamentId, playerId, rebuyAmount) => {
  try {
    const response = await fetch(
      `/api/tournaments/${tournamentId}/players/${playerId}/rebuy`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer your-api-key',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ rebuyAmount })
      }
    );
    
    const rebuyResult = await response.json();
    
    if (rebuyResult.rebuyProcessed) {
      console.log(`Rebuy successful. New entry count: ${rebuyResult.newEntryCount}`);
      // Update player balance and UI
      updatePlayerStats(rebuyResult);
    }
    
    return rebuyResult;
  } catch (error) {
    console.error('Rebuy processing failed:', error);
    throw error;
  }
};
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Registration Validation" icon="shield-check">
    * Validate player eligibility before registration
    * Check tournament capacity and timing
    * Verify payment information before processing
  </Card>

  <Card title="Session Management" icon="clock">
    * Monitor player connection status
    * Implement session timeout handling
    * Track player activity for analytics
  </Card>

  <Card title="Rebuy Handling" icon="credit-card">
    * Validate rebuy conditions before processing
    * Provide clear rebuy limit information
    * Handle failed payment scenarios gracefully
  </Card>

  <Card title="Error Recovery" icon="rotate-ccw">
    * Implement retry logic for failed registrations
    * Provide clear error messages to players
    * Log all registration attempts for debugging
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Results & Leaderboards" icon="trophy" href="/casino-integration/results-leaderboards">
    Access real-time tournament rankings and final results.
  </Card>

  <Card title="Webhooks & Events" icon="bell" href="/casino-integration/webhooks-events">
    Set up real-time notifications for player and tournament events.
  </Card>
</CardGroup>
