> ## 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.

# Internal APIs

> Core internal API endpoints for tournament configuration, player management, and status synchronization between Tournament System and Game Platform

# Internal APIs

The Internal APIs provide server-to-server communication between the Tournament System and Game Platform. These APIs enable tournament configuration retrieval, player list access, status monitoring, and tournament creation for hop-on/off formats.

## Authentication

All internal APIs require authentication via internal API keys in the Authorization header:

```http theme={null}
GET /internal/tournaments/12345/config
Authorization: Bearer {internal-api-key}
Content-Type: application/json
```

<Warning>
  **Internal API Keys** are high-privilege keys intended only for secure server-to-server communication. Never expose these keys in client-side code or public repositories.
</Warning>

## Tournament Configuration APIs

### Get Tournament Configuration

Retrieve complete tournament configuration for game room setup:

```http theme={null}
GET /internal/tournaments/{tournamentId}/config
Authorization: Bearer {internal-api-key}
```

**Response:**

```json theme={null}
{
  "tournamentId": "12345",
  "name": "Daily Championship",
  "gameSlug": "crash-classic",
  "status": "active",
  "maxPlayers": 100,
  "currentPlayers": 87,
  "minPlayers": 5,
  "startTime": "2024-01-15T20:00:00Z",
  "gameConfig": {
    "maxRounds": 10,
    "roundDuration": 300,
    "eliminationRate": 0.5,
    "gameRules": {
      "crashMultiplier": {
        "min": 1.0,
        "max": 100.0
      },
      "autoPlayEnabled": true,
      "maxBetAmount": 1000.0
    }
  },
  "prizePool": {
    "type": "percentage",
    "totalAmount": 870.00,
    "distribution": [50, 30, 20],
    "guaranteedPrize": 500.00
  },
  "roomId": "room_abc123",
  "roomUrl": "https://game.platform.com/room/abc123",
  "rebuyConfig": {
    "enabled": true,
    "fee": 10.00,
    "maxEntriesPerPlayer": 3,
    "deadline": "2024-01-15T20:30:00Z"
  },
  "operatorConfig": {
    "operatorId": "op_1234567890abcdef",
    "branding": {
      "primaryColor": "#8B5CF6",
      "logoUrl": "https://operator.com/logo.png"
    },
    "features": {
      "allowLateRegistration": false,
      "showTimer": true,
      "showLeaderboard": true
    }
  }
}
```

### Get Tournament Status

Monitor real-time tournament status and progress:

```http theme={null}
GET /internal/tournaments/{tournamentId}/status  
Authorization: Bearer {internal-api-key}
```

**Response:**

```json theme={null}
{
  "tournamentId": "12345",
  "status": "in_progress",
  "currentPlayers": 87,
  "maxPlayers": 100,
  "startTime": "2024-01-15T20:00:00Z",
  "actualStartTime": "2024-01-15T20:02:15Z",
  "estimatedEndTime": "2024-01-15T21:15:00Z",
  "currentRound": 3,
  "totalRounds": 5,
  "eliminations": 23,
  "gameRoom": {
    "roomId": "room_abc123",
    "activeConnections": 87,
    "lastActivity": "2024-01-15T20:25:30Z"
  },
  "prizePool": {
    "totalAmount": 870.00,
    "locked": true
  },
  "timing": {
    "roundStartTime": "2024-01-15T20:20:00Z",
    "roundEndTime": "2024-01-15T20:25:00Z",
    "nextRoundStart": "2024-01-15T20:30:00Z"
  }
}
```

### Tournament Status Values

| Status        | Description                           | Game Platform Actions                      |
| ------------- | ------------------------------------- | ------------------------------------------ |
| `scheduled`   | Tournament created, waiting for start | Prepare game room, wait for start signal   |
| `open`        | Registration open, not started        | Accept player connections, show lobby      |
| `in_progress` | Tournament actively running           | Manage gameplay, process player actions    |
| `completed`   | Tournament finished                   | Calculate final results, cleanup room      |
| `cancelled`   | Tournament cancelled                  | Cleanup room, handle player disconnections |

## Player Management APIs

### Get Tournament Players

Retrieve list of registered players for tournament setup:

```http theme={null}
GET /internal/tournaments/{tournamentId}/players
Authorization: Bearer {internal-api-key}
```

**Query Parameters:**

* `status` - Filter by player status (`active`, `registered`, `eliminated`)
* `includeEliminated` - Include eliminated players (default: false)
* `limit` - Results per page (default: 100, max: 500)

**Response:**

```json theme={null}
{
  "tournamentId": "12345",
  "players": [
    {
      "playerId": "tp_player_456",
      "internalPlayerId": "session_789", 
      "displayName": "PlayerName",
      "status": "active",
      "entryCount": 2,
      "totalPaid": 20.00,
      "registeredAt": "2024-01-15T19:30:00Z",
      "gameStats": {
        "currentPosition": 15,
        "points": 1250,
        "gamesPlayed": 8,
        "averageScore": 156.25,
        "currentRound": 3
      },
      "connectionInfo": {
        "lastActiveAt": "2024-01-15T20:25:30Z",
        "connectionStatus": "connected",
        "ipAddress": "192.168.1.100"
      },
      "permissions": ["play", "rebuy", "chat"],
      "metadata": {
        "vipLevel": "gold",
        "preferredLanguage": "en"
      }
    }
  ],
  "pagination": {
    "total": 87,
    "limit": 100,
    "offset": 0
  }
}
```

## Tournament Creation APIs (Hop-on/Off Only)

### Create Tournament

Create on-demand tournament for hop-on/off format:

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

{
  "name": "Crash #1642089600",
  "type": "hop_on_off",
  "gameSlug": "crash-classic", 
  "minPlayers": 5,
  "maxPlayers": 50,
  "startCondition": "min_players_reached",
  "entryFee": 5.00,
  "prizePool": {
    "type": "percentage",
    "distribution": [60, 25, 15]
  },
  "rebuyEnabled": true,
  "rebuyFee": 5.00,
  "maxEntriesPerPlayer": 2,
  "gameConfig": {
    "maxRounds": 5,
    "roundDuration": 180,
    "eliminationRate": 0.6
  }
}
```

**Response:**

```json theme={null}
{
  "tournamentId": "12346",
  "status": "scheduled",
  "name": "Crash #1642089600",
  "type": "hop_on_off", 
  "minPlayers": 5,
  "currentPlayers": 0,
  "startCondition": "min_players_reached",
  "created": "2024-01-15T20:30:00Z",
  "gameConfig": {
    "maxRounds": 5,
    "roundDuration": 180,
    "eliminationRate": 0.6
  }
}
```

### Remove Player (Hop-on/Off Only)

Remove player from tournament before start with refund:

```http theme={null}
DELETE /internal/tournaments/{tournamentId}/players/{playerId}
Authorization: Bearer {internal-api-key}
Content-Type: application/json

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

**Response:**

```json theme={null}
{
  "playerId": "tp_player_456",
  "tournamentId": "12346",
  "removed": true,
  "refundProcessed": true,
  "refundAmount": 10.00,
  "reason": "left_before_start",
  "remainingPlayers": 3,
  "tournamentStatus": "scheduled"
}
```

## Integration Examples

### Tournament Configuration Flow

```javascript theme={null}
// Retrieve tournament configuration for game room setup
const setupTournamentRoom = async (tournamentId) => {
  try {
    // Get tournament configuration
    const configResponse = await fetch(`/internal/tournaments/${tournamentId}/config`, {
      headers: {
        'Authorization': 'Bearer internal-api-key',
        'Content-Type': 'application/json'
      }
    });
    
    if (!configResponse.ok) {
      throw new Error(`Config fetch failed: ${configResponse.status}`);
    }
    
    const config = await configResponse.json();
    
    // Get registered players
    const playersResponse = await fetch(`/internal/tournaments/${tournamentId}/players`, {
      headers: {
        'Authorization': 'Bearer internal-api-key'
      }
    });
    
    const playersData = await playersResponse.json();
    
    // Initialize game room with configuration
    const gameRoom = await initializeGameRoom({
      tournamentId: config.tournamentId,
      gameConfig: config.gameConfig,
      players: playersData.players,
      prizePool: config.prizePool,
      rebuyConfig: config.rebuyConfig
    });
    
    console.log(`Tournament room initialized: ${gameRoom.roomId}`);
    return gameRoom;
    
  } catch (error) {
    console.error('Tournament setup failed:', error);
    throw error;
  }
};
```

### Hop-on/Off Tournament Creation

```javascript theme={null}
// Create new tournament when first player joins lobby
const createHopOnOffTournament = async (gameSlug, playerCount = 5) => {
  const timestamp = Math.floor(Date.now() / 1000);
  
  try {
    const response = await fetch('/internal/tournaments', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer internal-api-key',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: `${gameSlug} #${timestamp}`,
        type: 'hop_on_off',
        gameSlug: gameSlug,
        minPlayers: playerCount,
        maxPlayers: playerCount * 10,
        startCondition: 'min_players_reached',
        entryFee: 5.00,
        prizePool: {
          type: 'percentage',
          distribution: [60, 25, 15]
        },
        rebuyEnabled: true,
        rebuyFee: 5.00,
        maxEntriesPerPlayer: 3
      })
    });
    
    const tournament = await response.json();
    
    console.log(`Created hop-on/off tournament: ${tournament.tournamentId}`);
    return tournament;
    
  } catch (error) {
    console.error('Tournament creation failed:', error);
    throw error;
  }
};
```

### Tournament Status Monitoring

```javascript theme={null}
// Monitor tournament status with polling
class TournamentMonitor {
  constructor(tournamentId, intervalMs = 5000) {
    this.tournamentId = tournamentId;
    this.intervalMs = intervalMs;
    this.monitoring = false;
  }
  
  async startMonitoring() {
    this.monitoring = true;
    
    while (this.monitoring) {
      try {
        const response = await fetch(`/internal/tournaments/${this.tournamentId}/status`, {
          headers: {
            'Authorization': 'Bearer internal-api-key'
          }
        });
        
        const status = await response.json();
        
        // Handle status changes
        this.handleStatusChange(status);
        
        // Stop monitoring if tournament completed
        if (status.status === 'completed' || status.status === 'cancelled') {
          this.stopMonitoring();
          break;
        }
        
        // Wait before next poll
        await new Promise(resolve => setTimeout(resolve, this.intervalMs));
        
      } catch (error) {
        console.error('Status monitoring error:', error);
        // Continue monitoring despite errors
      }
    }
  }
  
  stopMonitoring() {
    this.monitoring = false;
    console.log(`Stopped monitoring tournament ${this.tournamentId}`);
  }
  
  handleStatusChange(status) {
    console.log(`Tournament ${this.tournamentId} status: ${status.status}`);
    console.log(`Players: ${status.currentPlayers}/${status.maxPlayers}`);
    
    if (status.currentRound) {
      console.log(`Round: ${status.currentRound}/${status.totalRounds}`);
    }
  }
}

// Usage
const monitor = new TournamentMonitor('12345');
monitor.startMonitoring();
```

## Error Handling

### Common Error Responses

#### Tournament Not Found

```json theme={null}
{
  "error": "tournament_not_found",
  "message": "Tournament with ID 12345 not found",
  "tournamentId": "12345"
}
```

#### Invalid Internal API Key

```json theme={null}
{
  "error": "unauthorized",
  "message": "Invalid internal API key",
  "code": "INVALID_INTERNAL_KEY"
}
```

#### Tournament Not Ready

```json theme={null}
{
  "error": "tournament_not_ready", 
  "message": "Tournament configuration not available - tournament may not be active",
  "tournamentStatus": "scheduled"
}
```

### Error Handling Best Practices

<CardGroup cols={2}>
  <Card title="Retry Logic" icon="rotate-ccw">
    Implement exponential backoff for failed requests with circuit breaker patterns
  </Card>

  <Card title="Status Validation" icon="check">
    Always validate tournament status before attempting operations
  </Card>

  <Card title="Graceful Degradation" icon="shield">
    Handle API failures gracefully without breaking game functionality
  </Card>

  <Card title="Monitoring" icon="chart-line">
    Monitor internal API response times and error rates
  </Card>
</CardGroup>

## Rate Limits

Internal APIs have higher rate limits than external APIs:

| Operation Type           | Limit         | Window     |
| ------------------------ | ------------- | ---------- |
| Tournament Configuration | 1000 requests | per minute |
| Player Data Retrieval    | 2000 requests | per minute |
| Status Monitoring        | 1000 requests | per minute |
| Tournament Creation      | 100 requests  | per minute |

## Next Steps

<CardGroup cols={2}>
  <Card title="JWT Authentication" icon="key" href="/game-platform-integration/jwt-authentication">
    Learn how to validate player JWT tokens for game access.
  </Card>

  <Card title="Event Reporting" icon="bell" href="/game-platform-integration/event-reporting">
    Report tournament events via SQS for external notifications.
  </Card>
</CardGroup>
