# Slidev API Deployment Guide

**Date:** 2025-10-09
**Issue:** #102 - End-to-End Demo Testing
**Status:** ✅ Code Ready, Awaiting Merge to Main

## Summary

The Slidev API endpoints have been successfully created as Motia API steps and are ready for deployment to Railway. The endpoints are committed to the `epic/slidev-control-mvp` branch and need to be merged to `main` to trigger Railway's auto-deployment.

## What Was Created

### 1. `/api/slidev/generate` - Deck Generation Endpoint

**File:** `apps/slide-system/steps/slidev-generate.step.ts` (320 lines)

**Method:** POST

**Request Body:**
```json
{
  "sessionId": "uuid-of-session",
  "templateId": "starter",
  "data": {
    "company": "Company Name",
    "tagline": "Company Tagline",
    "description": "About the company",
    "industry": "SaaS"
  }
}
```

**Response (200):**
```json
{
  "deckId": "abc1-def2-ghi3",
  "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/abc1-def2-ghi3/",
  "message": "Deck generated successfully"
}
```

**Features:**
- Generates unique 12-character deck ID
- Validates session exists in Supabase
- Creates simple HTML presentation with 3 slides
- Stores deck metadata in `slidev_decks` table
- Updates session with `slidev_url`
- Includes Supabase Realtime control integration
- Supports placeholder replacement ({{company}}, {{tagline}}, etc.)

**Error Responses:**
- 400: Missing required fields
- 404: Session not found
- 500: Generation failed

### 2. `/api/slidev/control` - Navigation Control Endpoint

**File:** `apps/slide-system/steps/slidev-control.step.ts` (300 lines)

**Method:** POST

**Headers:**
```
x-api-key: your-api-key-here
```

**Request Body:**
```json
{
  "deckId": "abc1-def2-ghi3",
  "command": "next",
  "slideId": "2"  // Optional, required for 'goto'
}
```

**Response (200):**
```json
{
  "success": true,
  "command": "next",
  "message": "Command broadcast successfully"
}
```

**Features:**
- API key authentication via `x-api-key` header
- Validates deck exists before sending command
- Broadcasts command via Supabase Realtime
- Supports commands: `next`, `prev`, `goto`
- Inserts command into `slide_control_commands` table
- Realtime subscription picks up command instantly

**Error Responses:**
- 400: Missing/invalid fields
- 401: Invalid or missing API key
- 404: Deck not found
- 500: Failed to broadcast command

## Deployment Steps

### Option 1: Merge to Main (Recommended)

This will trigger Railway's auto-deployment:

```bash
# 1. Switch to main branch in main worktree
cd /Users/lars/mycode/buzztrail/extension
git checkout main

# 2. Merge the epic branch
git merge epic/slidev-control-mvp

# 3. Push to main
git push origin main

# Railway will automatically:
# - Detect the push to main
# - Build new Docker image
# - Deploy to production
# - Run health checks
# - Route traffic to new deployment
```

**Deployment time:** ~5-10 minutes

### Option 2: Manual Railway Deployment

If you want to test before merging to main:

```bash
# From the epic worktree
cd /Users/lars/mycode/buzztrail/epic-slidev-control-mvp/apps/slide-system

# Trigger manual deployment via Railway CLI
railway up
```

## Environment Variables Needed

The following environment variables should already be set in Railway (verify in dashboard):

**Already Configured:**
- ✅ `SUPABASE_URL`
- ✅ `SUPABASE_SERVICE_KEY`
- ✅ `NODE_ENV=production`

**New Variable to Add:**
- ⚠️  `SLIDEV_API_KEY` - Generate a secure API key for control endpoint authentication
- ⚠️  `GITHUB_TOKEN` - (Optional for MVP, needed for actual GitHub Pages publishing)

**To add SLIDEV_API_KEY:**
```bash
# Generate a secure random key
SLIDEV_API_KEY=$(openssl rand -hex 32)

# Set in Railway
railway variables set SLIDEV_API_KEY=$SLIDEV_API_KEY
```

Or set it in Railway dashboard: https://railway.app

## Testing the Deployed Endpoints

Once deployed, test with these curl commands:

### Test Generate Endpoint
```bash
# First, create a test session (existing endpoint)
SESSION_RESPONSE=$(curl -s -X POST https://slide-system-production-5813.up.railway.app/demo-sessions \
  -H "Content-Type: application/json" \
  -d '{"session_type":"test","environment":"prod"}')

SESSION_ID=$(echo $SESSION_RESPONSE | jq -r '.session_id')

# Generate a deck
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d "{
    \"sessionId\": \"$SESSION_ID\",
    \"templateId\": \"starter\",
    \"data\": {
      \"company\": \"Test Company\",
      \"tagline\": \"We make great products\",
      \"description\": \"Learn about our amazing services\",
      \"industry\": \"SaaS\"
    }
  }"

# Expected response:
# {
#   "deckId": "abc1-def2-ghi3",
#   "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/abc1-def2-ghi3/",
#   "message": "Deck generated successfully"
# }
```

### Test Control Endpoint

```bash
# Replace with your generated deck ID and API key
DECK_ID="abc1-def2-ghi3"
API_KEY="your-api-key-here"

# Send next command
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: $API_KEY" \
  -d "{
    \"deckId\": \"$DECK_ID\",
    \"command\": \"next\"
  }"

# Expected response:
# {
#   "success": true,
#   "command": "next",
#   "message": "Command broadcast successfully"
# }
```

## Database Schema Required

The endpoints require these Supabase tables (should already exist):

### slidev_decks

```sql
CREATE TABLE IF NOT EXISTS slidev_decks (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deck_id TEXT UNIQUE NOT NULL,
  session_id UUID REFERENCES conversation_sessions(id),
  template_id TEXT NOT NULL DEFAULT 'starter',
  generation_data JSONB,
  deck_url TEXT,
  html_content TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_slidev_decks_deck_id ON slidev_decks(deck_id);
CREATE INDEX idx_slidev_decks_session_id ON slidev_decks(session_id);
```

### slide_control_commands

```sql
CREATE TABLE IF NOT EXISTS slide_control_commands (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deck_id TEXT NOT NULL,
  command TEXT NOT NULL,
  slide_id TEXT,
  timestamp TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_slide_control_commands_deck_id ON slide_control_commands(deck_id);
CREATE INDEX idx_slide_control_commands_timestamp ON slide_control_commands(timestamp);
```

### conversation_sessions update

Add `slidev_url` column if it doesn't exist:

```sql
ALTER TABLE conversation_sessions
ADD COLUMN IF NOT EXISTS slidev_url TEXT;
```

## Monitoring Deployment

### Watch Railway Logs

```bash
railway logs
```

Or view in Railway dashboard: https://railway.app

### Check Endpoint Health

```bash
# Test the new endpoints are accessible
curl -I https://slide-system-production-5813.up.railway.app/api/slidev/generate
curl -I https://slide-system-production-5813.up.railway.app/api/slidev/control
```

## After Deployment: Run Tests

Once the endpoints are live:

```bash
cd /Users/lars/mycode/buzztrail/epic-slidev-control-mvp

# Create .env file
cat > .env << 'EOF'
MOTIA_API_URL=https://slide-system-production-5813.up.railway.app
SLIDEV_API_KEY=your-api-key-here
API_BASE_URL=https://slide-system-production-5813.up.railway.app
SUPABASE_URL=https://dwdytxxqcvlrmyemonxz.supabase.co
SUPABASE_SERVICE_KEY=your-service-key
EOF

# Run performance tests
pnpm run test:performance

# Run concurrent tests
pnpm run test:concurrent

# Run E2E tests
pnpm test:e2e
```

## Known Limitations (MVP)

1. **GitHub Pages Publishing:** Not yet implemented - decks are stored in Supabase but not published to actual GitHub Pages
2. **Template System:** Only basic placeholder replacement - no actual Slidev build process yet
3. **HTML Presentation:** Simple 3-slide HTML deck instead of full Slidev features
4. **Deck Cleanup:** No automatic cleanup of old decks

These can be enhanced in future iterations after testing validates the architecture.

## Rollback Plan

If deployment causes issues:

```bash
# Revert the commit
git revert 54ab922

# Push to main
git push origin main

# Railway will auto-deploy the previous version
```

## Success Criteria

Deployment is successful when:
- ✅ `/api/slidev/generate` returns 200 with deck data
- ✅ `/api/slidev/control` returns 200 with success message
- ✅ Deck metadata is stored in Supabase
- ✅ Control commands are broadcast via Realtime
- ✅ No errors in Railway logs
- ✅ Existing `/demo-sessions` endpoint still works

## Next Steps After Deployment

1. ✅ Verify endpoints are live
2. ✅ Test with curl commands
3. ✅ Configure `.env` for tests
4. ✅ Execute performance tests (10 runs)
5. ✅ Execute concurrent tests (15 simultaneous)
6. ✅ Execute E2E test suite
7. ✅ Update test report with actual results
8. ✅ Close Issue #102

**Estimated time from deployment to test completion:** 3-4 hours

---

**Status:** Ready for deployment
**Commit:** `54ab922` - "Issue #102: Add Slidev API endpoints to slide-system"
**Branch:** `epic/slidev-control-mvp`
**Action Required:** Merge to `main` and push
