# Slidev Control API Documentation

## Overview

The Slidev Control API allows you to remotely control Slidev presentations by broadcasting navigation commands via Supabase Realtime.

**Base URL:** `https://your-api-domain.com/api/slidev`

## Authentication

All requests to the control endpoint require an API key passed in the `x-api-key` header.

```bash
x-api-key: your-api-key-here
```

## Endpoints

### POST /api/slidev/control

Broadcasts navigation commands to a Slidev presentation.

**Rate Limiting:** 10 commands per second per deck

#### Request Headers

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| `x-api-key` | string | Yes | API key for authentication |
| `Content-Type` | string | Yes | Must be `application/json` |

#### Request Body

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `deckId` | string | Yes | Deck identifier (format: `xxxx-xxxx-xxxx`) |
| `command` | string | Yes | Navigation command: `next`, `prev`, or `goto` |
| `slideId` | string | Conditional | Required when `command` is `goto` |

#### Response

**Success (200 OK):**

```json
{
  "success": true,
  "command": "next",
  "message": "Command broadcast successfully"
}
```

**Error Responses:**

- **400 Bad Request:** Invalid request body or missing required fields
  ```json
  {
    "error": "Validation failed",
    "details": "deckId must match format: xxxx-xxxx-xxxx (lowercase alphanumeric)"
  }
  ```

- **401 Unauthorized:** Invalid or missing API key
  ```json
  {
    "error": "Invalid or missing API key"
  }
  ```

- **404 Not Found:** Deck not found
  ```json
  {
    "error": "Deck not found",
    "details": "No deck exists with ID: a1b2-c3d4-e5f6"
  }
  ```

- **429 Too Many Requests:** Rate limit exceeded
  ```json
  {
    "message": "Too many control commands, please slow down"
  }
  ```

- **500 Internal Server Error:** Server error
  ```json
  {
    "error": "Failed to send command",
    "details": "Database connection failed"
  }
  ```

## Examples

### Navigate to Next Slide

```bash
curl -X POST https://your-api-domain.com/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: your-api-key-here" \
  -d '{
    "deckId": "a1b2-c3d4-e5f6",
    "command": "next"
  }'
```

### Navigate to Previous Slide

```bash
curl -X POST https://your-api-domain.com/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: your-api-key-here" \
  -d '{
    "deckId": "a1b2-c3d4-e5f6",
    "command": "prev"
  }'
```

### Navigate to Specific Slide

```bash
curl -X POST https://your-api-domain.com/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: your-api-key-here" \
  -d '{
    "deckId": "a1b2-c3d4-e5f6",
    "command": "goto",
    "slideId": "pricing"
  }'
```

### JavaScript/TypeScript Example

```typescript
async function controlSlide(deckId: string, command: 'next' | 'prev' | 'goto', slideId?: string) {
  const response = await fetch('https://your-api-domain.com/api/slidev/control', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': process.env.SLIDEV_API_KEY
    },
    body: JSON.stringify({
      deckId,
      command,
      ...(slideId && { slideId })
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Control command failed: ${error.error}`);
  }

  return response.json();
}

// Usage
await controlSlide('a1b2-c3d4-e5f6', 'next');
await controlSlide('a1b2-c3d4-e5f6', 'goto', 'pricing');
```

## Validation Rules

### deckId Format

- Must match pattern: `/^[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/`
- Example: `a1b2-c3d4-e5f6`
- Only lowercase alphanumeric characters and hyphens
- Three groups of 4 characters separated by hyphens

### command Values

- `next`: Navigate to the next slide
- `prev`: Navigate to the previous slide
- `goto`: Navigate to a specific slide (requires `slideId`)

### slideId (conditional)

- Required when `command` is `goto`
- Optional for `next` and `prev` commands
- String identifier for the target slide

## How It Works

1. **API Receives Command:** The control endpoint validates the API key and request body
2. **Database Verification:** Checks if the specified deck exists in Supabase
3. **Realtime Broadcast:** Inserts command into `slide_control_commands` table
4. **Slidev Client Listens:** Slidev presentation subscribes to Realtime events for its deck
5. **Navigation Executes:** Client receives event and executes navigation command

## Security

- **API Key Authentication:** Simple API key validation for MVP
- **Rate Limiting:** 10 commands per second per deck to prevent abuse
- **Future Enhancements:** Consider upgrading to JWT tokens or OAuth 2.0 for production

## Environment Variables

```bash
SLIDEV_API_KEY=your-random-api-key-here
```

Generate a secure API key:

```bash
# Generate a random 32-character API key
openssl rand -hex 32
```

## Performance

- **Response Time:** < 500ms target
- **Realtime Latency:** Typically 100-200ms for command delivery to clients
- **Rate Limiting:** 10 commands/second ensures smooth operation

## Troubleshooting

### 401 Unauthorized

- Verify `x-api-key` header is set correctly
- Check that `SLIDEV_API_KEY` environment variable matches

### 404 Deck Not Found

- Ensure the deck was generated successfully
- Verify deckId format matches `xxxx-xxxx-xxxx` pattern
- Check that deck exists in `slidev_decks` table

### 429 Rate Limit Exceeded

- Reduce command frequency to < 10 per second
- Implement client-side throttling
- Consider batching commands if appropriate

### 500 Internal Server Error

- Check Supabase connection and credentials
- Verify `slide_control_commands` table exists and Realtime is enabled
- Review server logs for detailed error messages

## Related Documentation

- [Slidev Generation API](./slidev-generate.md)
- [Supabase Realtime Documentation](https://supabase.com/docs/guides/realtime)
- [Slidev Official Documentation](https://sli.dev/)
