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

# Game Platform Integration Introduction

> Internal APIs for game systems to integrate with tournament functionality and manage real-time gameplay

# Game Platform Integration

The Game Platform Integration APIs provide internal access for game systems to integrate with tournament functionality, manage real-time gameplay, and handle player connections. These APIs enable seamless communication between the Tournament System and Game Platform.

## Overview

Game Platform Integration focuses on **internal APIs** that enable game systems to:

* Retrieve tournament configurations and player lists
* Validate JWT tokens for player authentication
* Create and manage game rooms for tournaments
* Report real-time events via SQS messaging
* Handle tournament state synchronization

<Info>
  **Integration Pattern**: Tournament System ↔ Game Platform via **internal APIs** with internal API key authentication.
</Info>

## API Categories

<CardGroup cols={2}>
  <Card title="Internal APIs" icon="server" href="/game-platform-integration/internal-apis">
    Tournament configuration, player lists, and status synchronization.
  </Card>

  <Card title="JWT Authentication" icon="key" href="/game-platform-integration/jwt-authentication">
    Player token validation and session management for game access.
  </Card>

  <Card title="Room Management" icon="users" href="/game-platform-integration/room-management">
    Game room creation, player connections, and session handling.
  </Card>

  <Card title="Real-time Communication" icon="bolt" href="/game-platform-integration/real-time-communication">
    PostMessage events, WebSocket connections, and UI integration.
  </Card>
</CardGroup>

## Authentication Model

All Game Platform Integration APIs use **internal API keys** for server-to-server authentication:

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

### Internal API Key Authentication

* **Server-to-Server**: Only for backend Game Platform services
* **High Privileges**: Access to all tournament data and operations
* **Rate Limiting**: Higher limits for internal system communication
* **Monitoring**: All internal API usage tracked and logged

## Core Integration Flows

### 1. Tournament Configuration Exchange

<Steps>
  <Step title="Retrieve Tournament Config">
    Game Platform fetches tournament settings via `GET /internal/tournaments/{id}/config`
  </Step>

  <Step title="Get Player List">
    Load registered players via `GET /internal/tournaments/{id}/players`
  </Step>

  <Step title="Monitor Tournament Status">
    Check tournament state via `GET /internal/tournaments/{id}/status`
  </Step>

  <Step title="Create Game Room">
    Initialize game room with tournament configuration and player data
  </Step>
</Steps>

### 2. Player Authentication & Connection

<Steps>
  <Step title="Receive JWT Token">
    Player connects with JWT token received from Casino System registration
  </Step>

  <Step title="Validate Token">
    Game Platform validates token via `POST /internal/auth/validate-token`
  </Step>

  <Step title="Connect to Room">
    Authenticated player joins tournament game room
  </Step>

  <Step title="Sync Player State">
    Load player progress and tournament position
  </Step>
</Steps>

### 3. Real-time Event Reporting

<Tabs>
  <Tab title="SQS Events">
    **Tournament Events** sent to AWS SQS:

    * `room.tournament.started` - Tournament begins in game room
    * `room.tournament.completed` - Tournament finishes with results
    * `player.score.updated` - Real-time player score changes
    * `room.player.connected` - Player joins game room
    * `room.player.disconnected` - Player leaves game room
  </Tab>

  <Tab title="PostMessage Communication">
    **Browser Events** for Casino UI integration:

    * `tournament.connected` - Player connected to tournament
    * `tournament.started` - Tournament gameplay began
    * `tournament.completed` - Tournament finished
    * `rebuy.requested` - Player wants to rebuy
    * `player.eliminated` - Player eliminated from tournament
  </Tab>
</Tabs>

## Data Flow Architecture

```mermaid theme={null}
graph TD
    A[Game Platform] -->|Internal APIs| B[Tournament System]
    B -->|Configuration| A
    A -->|JWT Validation| B
    A -->|SQS Events| C[Event Processing]
    C -->|Webhooks| D[Casino System]
    A -->|postMessage| E[Casino UI]
    
    style A fill:#e8f5e9
    style B fill:#f3e5f5
    style C fill:#fce4ec
    style D fill:#e1f5fe
    style E fill:#fff3e0
```

### Communication Patterns

* **Game Platform → Tournament System**: Internal APIs for config and status
* **Tournament System → Game Platform**: Configuration responses and validation
* **Game Platform → Event System**: SQS events for external notifications
* **Game Platform → Casino UI**: postMessage for real-time UI updates

## API Endpoints Overview

### Tournament Configuration

```http theme={null}
GET /internal/tournaments/{id}/config        # Get tournament configuration
GET /internal/tournaments/{id}/players       # Get registered players
GET /internal/tournaments/{id}/status        # Get current tournament status
```

### Authentication & Validation

```http theme={null}
POST /internal/auth/validate-token           # Validate player JWT tokens
GET /internal/auth/player/{id}/permissions   # Get player permissions
```

### Tournament Management (Hop-on/Off Only)

```http theme={null}
POST /internal/tournaments                   # Create tournament (hop-on/off)
DELETE /internal/tournaments/{id}/players/{player}  # Remove player with refund
```

### Event Reporting

```http theme={null}
POST /internal/tournaments/{id}/events       # Report tournament events
POST /internal/tournaments/{id}/results      # Submit tournament results
```

## Integration Patterns by Tournament Type

### Scheduled Tournaments

* **Standard Flow**: Tournament created by Casino System via external API
* **Game Platform Role**: Receives configuration, manages gameplay, reports events
* **APIs Used**: Configuration retrieval, JWT validation, event reporting

### Hop-On/Off Tournaments

* **Extended Flow**: Game Platform creates tournaments via internal API
* **Game Platform Role**: Creates tournaments, manages lobby, handles refunds
* **APIs Used**: Tournament creation, configuration, player management, event reporting

## Error Handling & Best Practices

### Internal API Error Codes

* `401 Unauthorized` - Invalid internal API key
* `403 Forbidden` - Internal API key lacks required scope
* `404 Not Found` - Tournament or resource not found
* `422 Unprocessable Entity` - Invalid request data
* `429 Too Many Requests` - Rate limit exceeded (higher limits than external APIs)
* `500 Internal Server Error` - System error

### Rate Limiting

* **Tournament Configuration**: 1000 requests per minute
* **JWT Validation**: 5000 requests per minute
* **Event Reporting**: 10000 requests per minute
* **General Internal APIs**: 2000 requests per minute

### Retry & Circuit Breaker Patterns

<Warning>
  Implement circuit breaker patterns for internal API calls to prevent cascade failures between Tournament System and Game Platform.
</Warning>

```javascript theme={null}
const circuitBreaker = {
  failureThreshold: 5,
  resetTimeout: 60000,
  monitor: (error) => {
    if (error.status >= 500) {
      circuitBreaker.failures++;
    }
  }
};
```

## Integration Examples

### Tournament Configuration Retrieval

```javascript theme={null}
const getTournamentConfig = async (tournamentId) => {
  const response = await fetch(`/internal/tournaments/${tournamentId}/config`, {
    headers: {
      'Authorization': 'Bearer internal-api-key',
      'Content-Type': 'application/json'
    }
  });
  
  const config = await response.json();
  return {
    gameConfig: config.gameConfig,
    maxPlayers: config.maxPlayers,
    prizePool: config.prizePool,
    roomId: config.roomId
  };
};
```

### JWT Token Validation

```javascript theme={null}
const validatePlayerToken = async (jwtToken) => {
  const response = await fetch('/internal/auth/validate-token', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer internal-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ token: jwtToken })
  });
  
  if (response.ok) {
    const validation = await response.json();
    return {
      valid: validation.valid,
      tournamentId: validation.tournamentId,
      playerId: validation.playerId,
      permissions: validation.permissions
    };
  }
  
  throw new Error('Token validation failed');
};
```

## Security Considerations

### Internal API Key Management

* **Secure Storage**: Store internal API keys in secure credential systems
* **Environment Isolation**: Separate keys for development, staging, production
* **Key Rotation**: Regular rotation of internal API keys
* **Access Logging**: Complete audit trail of internal API usage

### Network Security

* **Private Networks**: Internal APIs should only be accessible within private networks
* **TLS Encryption**: All internal communication encrypted with TLS 1.3
* **IP Restrictions**: Whitelist Game Platform IP addresses
* **Monitoring**: Real-time monitoring of internal API traffic patterns

## Next Steps

<CardGroup cols={2}>
  <Card title="Internal APIs" icon="server" href="/game-platform-integration/internal-apis">
    Detailed documentation of all internal API endpoints and their usage.
  </Card>

  <Card title="JWT Authentication" icon="shield-check" href="/game-platform-integration/jwt-authentication">
    Player token validation and authentication flow implementation.
  </Card>

  <Card title="Real-time Events" icon="bolt" href="/game-platform-integration/real-time-communication">
    SQS event reporting and postMessage communication patterns.
  </Card>

  <Card title="Room Management" icon="users" href="/game-platform-integration/room-management">
    Game room creation, player connections, and session management.
  </Card>
</CardGroup>
