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

# Casino Integration Introduction

> External APIs for casino operators to integrate tournament functionality into their platforms

# Casino System Integration

The Casino Integration APIs provide external access for casino operators to integrate tournament functionality into their platforms. These are the primary APIs used for tournament management, player registration, results access, and event handling.

## Overview

Casino System Integration focuses on **external APIs** that enable casino operators to:

* Create and manage tournaments
* Register and manage players
* Access real-time leaderboards and results
* Receive webhook notifications for tournament events
* Handle player transactions (buy-ins, rebuys, refunds)

<Info>
  **Integration Pattern**: Casino System ↔ Tournament System via **external APIs** with operator authentication and role-based permissions.
</Info>

## API Categories

<CardGroup cols={2}>
  <Card title="Authentication & Security" icon="shield" href="/casino-integration/authentication">
    API key management, role-based permissions, and security best practices.
  </Card>

  <Card title="Tournament Management" icon="trophy" href="/casino-integration/tournament-management">
    Create, update, cancel, and monitor tournaments across your platform.
  </Card>

  <Card title="Player Management" icon="users" href="/casino-integration/player-management">
    Register players, handle rebuys, manage sessions, and track participation.
  </Card>

  <Card title="Results & Leaderboards" icon="chart-bar" href="/casino-integration/results-leaderboards">
    Access real-time rankings, final results, prize distributions, and historical data.
  </Card>
</CardGroup>

## Authentication Model

All Casino Integration APIs use **operator API keys** with role-based permissions:

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

### Permission Structure

* `tournaments.read` - View tournaments and status
* `tournaments.write` - Create and update tournaments
* `tournaments.delete` - Cancel tournaments
* `players.read` - View player data and registrations
* `players.write` - Register and manage players
* `results.read` - Access results and leaderboard data

## Common Integration Patterns

### 1. Tournament Lifecycle Management

<Steps>
  <Step title="Create Tournament">
    Casino System creates tournament via `POST /api/tournaments`
  </Step>

  <Step title="Player Registration">
    Players register through `POST /api/tournaments/{id}/players`
  </Step>

  <Step title="Tournament Monitoring">
    Monitor status via `GET /api/tournaments/{id}/status`
  </Step>

  <Step title="Results Access">
    Retrieve results via `GET /api/tournaments/{id}/results`
  </Step>
</Steps>

### 2. Real-time Event Handling

<Tabs>
  <Tab title="Webhook Events">
    **HTTP Webhooks** for real-time notifications:

    * Tournament started/completed events
    * Player registration/elimination notifications
    * Results and prize distribution updates
    * System status changes and alerts
  </Tab>

  <Tab title="SQS Events">
    **AWS SQS** for reliable event delivery:

    * Guaranteed message delivery with retry logic
    * High-throughput event processing
    * Dead letter queue handling for failed events
    * Integration with existing AWS infrastructure
  </Tab>
</Tabs>

## API Endpoints Overview

### Tournament Management

```http theme={null}
POST /api/tournaments                    # Create tournament
GET /api/tournaments                     # List tournaments  
GET /api/tournaments/{id}                # Get tournament details
PUT /api/tournaments/{id}                # Update tournament
DELETE /api/tournaments/{id}             # Cancel tournament
GET /api/tournaments/{id}/status         # Get tournament status
```

### Player Management

```http theme={null}
POST /api/tournaments/{id}/players       # Register player
GET /api/tournaments/{id}/players        # List tournament players
DELETE /api/tournaments/{id}/players/{player}  # Remove player
POST /api/tournaments/{id}/players/{player}/rebuy  # Process rebuy
```

### Results & Leaderboards

```http theme={null}
GET /api/tournaments/{id}/leaderboard    # Real-time rankings
GET /api/tournaments/{id}/results        # Final results
GET /api/tournaments/{id}/prize-pool     # Prize pool calculation
GET /api/tournaments/{id}/events         # Tournament event history
```

## Data Flow Architecture

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

### Communication Patterns

* **Casino → Tournament**: External APIs with operator authentication
* **Tournament → Casino**: SQS events and HTTP webhooks
* **UI Integration**: postMessage events between game and casino interfaces
* **Real-time Updates**: WebSocket connections for live leaderboards

## Error Handling & Best Practices

### HTTP Status Codes

* `200 OK` - Successful operation
* `201 Created` - Resource created successfully
* `400 Bad Request` - Invalid request parameters
* `401 Unauthorized` - Invalid or missing API key
* `403 Forbidden` - Insufficient permissions
* `404 Not Found` - Tournament or resource not found
* `409 Conflict` - Resource conflict (duplicate registration)
* `429 Too Many Requests` - Rate limit exceeded
* `500 Internal Server Error` - Server error

### Rate Limiting

* **Standard Operations**: 100 requests per minute per API key
* **Tournament Creation**: 10 requests per minute per API key
* **Player Registration**: 200 requests per minute per API key
* **Results Access**: 500 requests per minute per API key

### Retry Logic

<Warning>
  Implement exponential backoff for failed requests with maximum retry limits to prevent overwhelming the system.
</Warning>

```javascript theme={null}
const retryDelay = Math.min(1000 * Math.pow(2, retryCount), 30000);
setTimeout(() => retryRequest(), retryDelay);
```

## Integration Examples

### Basic Tournament Creation

```javascript theme={null}
const response = await fetch('/api/tournaments', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Daily Championship',
    startTime: '2024-01-15T20:00:00Z',
    gameSlug: 'crash-classic', 
    maxPlayers: 100,
    entryFee: 10.00
  })
});

const tournament = await response.json();
console.log(`Tournament created: ${tournament.tournamentId}`);
```

### Player Registration

```javascript theme={null}
const registration = await fetch(`/api/tournaments/${tournamentId}/players`, {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    userId: 'player_123',
    displayName: 'PlayerName',
    buyInAmount: 10.00
  })
});

const result = await registration.json();
// Player receives JWT token and game URL for tournament access
```

## Multi-Tenant Architecture

<Info>
  All APIs are scoped to your operator account. You can only access tournaments and players within your operator tenant.
</Info>

### Operator Isolation

* **Data Scoping**: All data automatically filtered by operator ID
* **API Key Scoping**: Keys only access data within operator boundaries
* **Resource Isolation**: No cross-operator data access or interference
* **Independent Configuration**: Webhook URLs, settings, and preferences per operator

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication Setup" icon="key" href="/casino-integration/authentication">
    Set up API keys and configure role-based permissions.
  </Card>

  <Card title="Your First Tournament" icon="trophy" href="/casino-integration/tournament-management">
    Create and manage your first tournament integration.
  </Card>

  <Card title="Webhook Configuration" icon="link" href="/casino-integration/webhooks-events">
    Configure real-time event notifications for your system.
  </Card>

  <Card title="Testing & Debugging" icon="bug" href="/casino-integration/testing-debugging">
    Tools and techniques for testing your integration.
  </Card>
</CardGroup>
