# PRD: Backend API for Client/Admin UI

## Document Control
- **Status**: Draft
- **Priority**: P1
- **Estimated Effort**: 4-6 weeks
- **Owner**: TBD
- **Created**: 2025-10-04
- **Last Updated**: 2025-10-08T16:30:01Z
- **Related PRDs**:
  - `ui-for-clients-and-admins.md` (frontend)
  - `customer-persona-lifecycle-management.md` (persona schema)
  - `tavus-conversation-management-system.md` (session schema)
  - `core-presentation-engine/slidev-control-mvp.md` (slide deck system with scalability architecture)

## Executive Summary

Build a Node.js/TypeScript API layer that sits between the UI and Supabase, providing:
- Client-safe persona management (limited field editing)
- Session and transcript access with proper RLS enforcement
- Annotation submission with Langfuse integration
- Client request form handling
- Admin-only cross-client operations
- Webhook handlers for Tavus and Langfuse events

**Key Decision**: UI calls our API only, never directly contacts Supabase, Tavus, AWS, or Langfuse.

## Key Architectural Decisions

### 1. Persona Configuration via Tavus UI
**Problem**: Clients edit personas in Tavus's UI, not ours. How does our system know to version?

**Solution**: Manual sync trigger (Tavus doesn't send persona change webhooks)
```typescript
// Admin clicks "Sync from Tavus" in UI
POST /api/admin/personas/:id/sync-from-tavus

// Backend:
1. Fetch latest from Tavus: GET https://tavusapi.com/v2/personas/:tavus_persona_id
2. Compare with our DB (phase1_system_prompt, phase1_objectives, etc.)
3. If changed: increment version by 1 (v5 → v6), update DB
4. Return updated persona
```

**Alternative**: Background job polls Tavus every 15 minutes for all personas, auto-syncs changes.

### 2. Client-Editable Persona Fields
Clients can ONLY change:
- **NOTHING** - All persona fields are read-only for clients

Clients CANNOT change:
- ❌ Description (read-only, must request changes via form)
- ❌ Voice (read-only, must request via form submission)
- ❌ Prompts (edited in Tavus UI by admins)
- ❌ Objectives/guardrails (admin-only)
- ❌ Emotion detection (removed from client access)
- ❌ Interaction mode (removed from client access)
- ❌ Avatar (removed from client access)

**Client Action**: Use "Request Changes" form to submit modification requests

**Version Bump Rules**:
- Admin edits in Tavus → Manual sync detects changes → Auto-increment version
- Admin changes slide deck association → Auto-increment version
- Admin changes status (testing→staging→production) → Auto-increment version

### 3. No Real-Time Updates (WebSockets)
- ✅ **Removed**: `session_live_state` table entirely
- ✅ **Removed**: Supabase Realtime subscriptions
- ✅ **Decision**: Admins view conversations AFTER completion (not live monitoring)
- UI uses standard REST polling if needed (refresh button)

### 4. Recording Playback - OUT OF SCOPE
**Decision**: Video/audio playback is complex (separate streams, slide sync, multi-format) → Separate PRD

**For this PRD**:
- API returns list of recording file paths (S3 keys)
- UI shows "Recording playback coming soon" placeholder
- No signed URLs, no playback UI

**Future PRD** (`recording-playback-system.md`) will handle:
- Multi-stream video reconstruction (avatar video + customer video + slides)
- Audio-only playback for voice mode
- Transcript-synced playback
- HLS/DASH streaming

### 5. Cross-Client Analytics (Admin)
**Solution**: Admin RLS policy (not service role bypass)

```sql
-- Admins see everything via RLS
CREATE POLICY admin_full_access ON client_personas
  FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM auth.users
      WHERE id = auth.uid() AND role = 'admin'
    )
  );
```

Admin uses regular authenticated requests, RLS allows access to all clients' data.

## API Endpoints

### Authentication
All endpoints require Supabase JWT in `Authorization: Bearer <token>` header.

Backend validates JWT and extracts:
- `user_id` (auth.uid())
- `role` ('client' | 'admin')
- `client_id` (for client users)

---

### Persona Management

#### `GET /api/personas`
**Auth**: Client or Admin
**Purpose**: List personas for current user

**Client behavior**:
- Filters by `client_id` (from JWT)
- Only shows `status IN ('staging', 'production')`

**Admin behavior**:
- Shows ALL personas across all clients (RLS admin policy)
- Can filter by `?client_id=xxx` or `?status=testing`

**Response**:
```json
{
  "personas": [
    {
      "id": "uuid",
      "persona_name": "Sophie Sales Assistant",
      "description": "Friendly sales rep for discovery calls",
      "version": 12,
      "status": "production",
      "total_sessions": 47,
      "last_session_at": "2025-10-03T14:22:00Z",
      "selected_voice_name": "Professional Sarah",
      "phase1_objectives": ["Understand pain points", "Qualify budget"],
      "phase1_guardrails": ["Never discuss pricing"]
    }
  ]
}
```

---

#### `GET /api/personas/:id`
**Auth**: Client (own personas only) or Admin (all)
**Purpose**: Get full persona details

**Validation**:
- Client: Must own this persona (check `client_id`)
- Admin: No restriction

**Response**:
```json
{
  "persona": {
    "id": "uuid",
    "client_id": "uuid",
    "tavus_persona_id": "tavus_xxx",
    "persona_name": "Sophie Sales Assistant",
    "description": "...",
    "version": 12,
    "status": "production",

    // Read-only prompt info (clients can view but not edit)
    "phase1_system_prompt": "You are a friendly sales assistant...",
    "phase1_conversation_style": "professional, consultative",
    "phase1_objectives": ["Understand pain points"],
    "phase1_guardrails": ["Never discuss pricing"],

    // Client-editable
    "selected_voice_name": "Professional Sarah",

    // Metadata
    "total_sessions": 47,
    "last_session_at": "2025-10-03T14:22:00Z",
    "created_at": "2025-09-01T10:00:00Z",
    "updated_at": "2025-10-03T12:00:00Z"
  }
}
```

---

#### `PUT /api/personas/:id/settings`
**Auth**: Client (own personas only) or Admin (all)
**Purpose**: Update client-editable fields only

**Request**:
```json
{
  "description": "Updated description for sales demo persona"
}
```

**Backend logic**:
1. Validate client owns persona (or is admin)
2. Update only allowed field: `description`
3. Database trigger auto-increments version by 1 (v3 → v4)
4. Trigger inserts version history record
5. Update `updated_at` timestamp

**Response**:
```json
{
  "persona": { /* updated persona */ },
  "previous_version": 3,
  "new_version": 4
}
```

---

#### `POST /api/admin/personas/:id/sync-from-tavus`
**Auth**: Admin only
**Purpose**: Fetch latest persona config from Tavus and sync to our DB

**Backend logic**:
1. Fetch from Tavus: `GET https://tavusapi.com/v2/personas/:tavus_persona_id`
2. Compare fields: `phase1_system_prompt`, `phase1_objectives`, `phase1_guardrails`, etc.
3. If changed:
   - Database trigger increments version by 1 (v5 → v6)
   - Update DB
   - Trigger inserts version history
4. Return updated persona

**Response**:
```json
{
  "persona": { /* updated persona */ },
  "changes_detected": true,
  "previous_version": 5,
  "new_version": 6,
  "changed_fields": ["phase1_system_prompt", "phase1_objectives"]
}
```

---

#### `GET /api/personas/:id/versions`
**Auth**: Client or Admin
**Purpose**: List version history

**Response**:
```json
{
  "versions": [
    {
      "version": 12,
      "created_at": "2025-10-03T12:00:00Z",
      "changed_by": "admin_user_id",
      "changed_fields": ["phase1_system_prompt"]
    },
    {
      "version": 11,
      "created_at": "2025-10-01T10:00:00Z",
      "changed_by": "client_user_id",
      "changed_fields": ["description"]
    }
  ]
}
```

---

### Session/Conversation Management

#### `GET /api/sessions`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: List conversation sessions

**Query params**:
- `?persona_id=xxx` - Filter by persona
- `?start_date=2025-10-01` - Date range
- `?end_date=2025-10-04`
- `?status=completed` - Filter by status
- `?limit=50&offset=0` - Pagination

**Response**:
```json
{
  "sessions": [
    {
      "id": "uuid",
      "persona_id": "uuid",
      "persona_name": "Sophie Sales Assistant",
      "phase1_started_at": "2025-10-03T14:00:00Z",
      "phase1_ended_at": "2025-10-03T14:05:32Z",
      "phase2_started_at": "2025-10-03T14:05:42Z",
      "phase2_ended_at": "2025-10-03T14:18:15Z",
      "total_duration_seconds": 1095,
      "status": "completed",
      "participant_name": "John Prospect"
    }
  ],
  "total": 147,
  "limit": 50,
  "offset": 0
}
```

---

#### `GET /api/sessions/:id`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: Get full session details

**Response**:
```json
{
  "session": {
    "id": "uuid",
    "client_id": "uuid",
    "persona_id": "uuid",

    // Phase 1 (Tavus Discovery)
    "tavus_conversation_id": "tavus_conv_xxx",
    "phase1_started_at": "2025-10-03T14:00:00Z",
    "phase1_ended_at": "2025-10-03T14:05:32Z",
    "phase1_duration_seconds": 332,
    "phase1_objectives": {
      "achieved": ["Understand pain points", "Qualify budget"],
      "not_achieved": ["Identify decision maker"]
    },

    // Intermission
    "intermission_started_at": "2025-10-03T14:05:32Z",
    "intermission_ended_at": "2025-10-03T14:05:42Z",
    "slide_customization": {
      "slides_shown": [1, 2, 3, 5, 7],
      "slides_skipped": [4, 6]
    },

    // Phase 2 (Pipecat Slide Demo)
    "pipecat_session_id": "pipecat_xxx",
    "phase2_started_at": "2025-10-03T14:05:42Z",
    "phase2_ended_at": "2025-10-03T14:18:15Z",
    "phase2_duration_seconds": 753,

    // Overall
    "total_duration_seconds": 1095,
    "status": "completed",

    // Participant
    "participant_name": "John Prospect",
    "participant_email": "john@example.com",

    // Platform
    "platform": "daily",
    "daily_room_name": "buzztrail-demo-abc123"
  }
}
```

---

#### `GET /api/sessions/:id/transcript`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: Get full transcript (Phase 1 + Phase 2)

**Response**:
```json
{
  "transcript": {
    "phase1": [
      {
        "timestamp": 0,
        "speaker": "persona",
        "text": "Hi! I'm Sophie. How can I help you today?",
        "confidence": 0.98
      },
      {
        "timestamp": 3.2,
        "speaker": "participant",
        "text": "I'm looking for a solution to automate our sales demos.",
        "confidence": 0.95
      }
    ],
    "phase2": [
      {
        "timestamp": 0,
        "speaker": "persona",
        "text": "Great! Let me show you how our platform works.",
        "slide_number": 1
      }
    ]
  }
}
```

---

#### `GET /api/sessions/:id/recordings`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: List recording files (NO playback URLs - out of scope)

**Response**:
```json
{
  "recordings": {
    "recording_s3_base_path": "clients/client-uuid/sessions/session-uuid/",
    "files": [
      {
        "key": "phase1_avatar_audio.wav",
        "size_bytes": 5242880,
        "duration_seconds": 332
      },
      {
        "key": "phase1_avatar_video.mp4",
        "size_bytes": 15728640,
        "duration_seconds": 332
      },
      {
        "key": "phase1_customer_audio.wav",
        "size_bytes": 5242880,
        "duration_seconds": 332
      },
      {
        "key": "phase2_avatar_audio.wav",
        "size_bytes": 11796480,
        "duration_seconds": 753
      },
      {
        "key": "phase2_slides_screenshare.mp4",
        "size_bytes": 31457280,
        "duration_seconds": 753
      }
    ],
    "note": "Playback UI coming in separate release (multi-stream reconstruction required)"
  }
}
```

---

### Annotation Management

#### `POST /api/annotations`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: Submit annotation for conversation

**Request**:
```json
{
  "session_id": "uuid",
  "transcript_line_number": 42,
  "category": "behavior_issue",
  "feedback": "Persona interrupted the participant here",
  "severity": "medium"
}
```

**Backend logic**:
1. Validate client owns this session (or is admin)
2. Insert into `annotations` table
3. POST to Langfuse API (create trace with annotation)
4. Store `langfuse_trace_id` in annotations row

**Response**:
```json
{
  "annotation": {
    "id": "uuid",
    "session_id": "uuid",
    "client_id": "uuid",
    "category": "behavior_issue",
    "feedback": "...",
    "severity": "medium",
    "status": "pending_review",
    "langfuse_trace_id": "trace_xxx",
    "created_at": "2025-10-04T10:00:00Z"
  }
}
```

---

#### `GET /api/sessions/:id/line-reviews`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: Get all per-line reviews for a session (PRIMARY feedback mechanism)

**Response**:
```json
{
  "lineReviews": [
    {
      "id": "uuid",
      "lineNumber": 12,
      "transcriptText": "Based on your budget of $50k...",
      "speaker": "ai",
      "rating": "critical",  // 'good' | 'needs_improvement' | 'critical'
      "comment": "Budget was $100k, not $50k - AI misheard",
      "createdBy": "user-uuid",
      "createdByName": "Sarah Johnson",
      "createdAt": "2025-10-04T10:00:00Z",
      "status": "pending_review"
    }
  ],
  "summary": {
    "totalAILines": 18,
    "reviewedLines": 15,
    "percentComplete": 83,
    "breakdown": {
      "good": 10,
      "needs_improvement": 3,
      "critical": 2
    },
    "score": 67  // 0-100 calculated from ratings
  }
}
```

**Note**: This endpoint returns ALL reviews from ALL team members for multi-reviewer visibility

---

#### `POST /api/sessions/:id/line-reviews`
**Auth**: Client or Admin
**Purpose**: Submit a per-line review (one-click feedback)

**Request**:
```json
{
  "lineNumber": 12,
  "transcriptText": "Based on your budget of $50k...",
  "rating": "critical",  // 'good' | 'needs_improvement' | 'critical'
  "comment": "Budget was $100k, not $50k - AI misheard",  // Optional for 'good', required for others
  "createRequest": true  // If true, also creates client_request
}
```

**Backend logic**:
1. Validate session belongs to client
2. Upsert into `line_annotations` table (one review per user per line)
3. If `createRequest: true`, create entry in `client_requests` table linked to this review
4. POST to Langfuse API for admin review queue
5. Calculate updated session score

**Response**:
```json
{
  "review": {
    "id": "uuid",
    "lineNumber": 12,
    "rating": "critical",
    "comment": "...",
    "createdAt": "2025-10-04T10:00:00Z"
  },
  "request": {  // If createRequest was true
    "id": "uuid",
    "requestNumber": "REQ-042"
  },
  "sessionScore": 67  // Updated overall score
}
```

---

#### `GET /api/line-reviews`
**Auth**: Client (own reviews) or Admin (all)
**Purpose**: List line reviews with filters (for admin dashboard)

**Query params**:
- `?session_id=xxx`
- `?rating=critical`
- `?status=pending_review`
- `?client_id=xxx` (admin only)

---

#### `GET /api/sessions/:id/conversation-summary`
**Auth**: Client (own sessions) or Admin (all)
**Purpose**: Get auto-aggregated conversation summary from line reviews

**Response**:
```json
{
  "summary": {
    "score": 67,
    "totalLines": 18,
    "reviewedLines": 15,
    "breakdown": {
      "good": 10,
      "needs_improvement": 3,
      "critical": 2
    },
    "keyIssues": [
      {
        "lineNumber": 12,
        "issue": "Budget was $100k, not $50k - AI misheard",
        "rating": "critical"
      },
      {
        "lineNumber": 7,
        "issue": "Could be more empathetic here",
        "rating": "needs_improvement"
      }
    ],
    "improvementRequests": [
      {
        "id": "uuid",
        "requestNumber": "REQ-042",
        "lineNumber": 12,
        "description": "Fix budget capture accuracy"
      }
    ],
    "recommendations": [
      "AI should wait for customer to finish speaking (appeared in 2 lines)",
      "Review pricing information accuracy"
    ]
  }
}
```

---

### Client Request Management

#### `POST /api/client-requests`
**Auth**: Client or Admin
**Purpose**: Submit persona change request (can be linked to line review)

**Request**:
```json
{
  "persona_id": "uuid",
  "change_type": "behavior_adjustment",
  "description": "Please make the persona more enthusiastic when discussing features",
  "client_priority": "medium",
  "source_type": "line_review",  // Optional: 'line_review' | 'standalone'
  "source_id": "line-review-uuid",  // Optional: UUID of line_annotations record
  "session_id": "session-uuid",  // Optional: for context
  "line_number": 12  // Optional: if from line review
}
```

**Backend logic**:
1. Validate client owns persona
2. Insert into `client_requests` table with source linkage
3. Set status = 'new'
4. Generate request number (REQ-XXX)

**Response**:
```json
{
  "request": {
    "id": "uuid",
    "requestNumber": "REQ-042",
    "persona_id": "uuid",
    "change_type": "behavior_adjustment",
    "description": "...",
    "client_priority": "medium",
    "status": "new",
    "source": {
      "type": "line_review",
      "lineNumber": 12,
      "sessionId": "session-uuid"
    },
    "created_at": "2025-10-04T10:00:00Z"
  }
}
```

---

#### `GET /api/client-requests`
**Auth**: Client (own requests) or Admin (all)
**Purpose**: List client requests with line review context

**Client behavior**: Sees only their requests
**Admin behavior**: Sees all requests across clients (can filter by `?client_id=xxx`)

**Response**:
```json
{
  "requests": [
    {
      "id": "uuid",
      "requestNumber": "REQ-042",
      "persona_id": "uuid",
      "persona_name": "Sophie Sales Assistant",
      "client_id": "client-uuid",
      "client_name": "Acme Corp",
      "change_type": "behavior_adjustment",
      "description": "Fix budget capture accuracy",
      "client_priority": "high",
      "status": "under_review",
      "source": {
        "type": "line_review",
        "sessionId": "session-uuid",
        "conversationNumber": "12345",
        "lineNumber": 12,
        "timestamp": "[03:42]",
        "aiResponse": "Based on your budget of $50k...",
        "reviewRating": "critical",
        "reviewComment": "Budget was $100k, not $50k - AI misheard"
      },
      "assigned_to": "admin-user-uuid",
      "admin_notes": "Reviewing STT configuration...",
      "created_at": "2025-10-04T10:00:00Z",
      "updated_at": "2025-10-04T15:30:00Z"
    },
    {
      "id": "uuid",
      "requestNumber": "REQ-043",
      "persona_id": "uuid",
      "persona_name": "Sophie Sales Assistant",
      "client_id": "client-uuid",
      "client_name": "Acme Corp",
      "change_type": "voice_change",
      "description": "Change voice to sound more authoritative",
      "client_priority": "low",
      "status": "new",
      "source": {
        "type": "standalone"  // No line review context
      },
      "created_at": "2025-10-03T14:00:00Z"
    }
  ]
}
```

**Note**: Admin view includes `client_id` and `client_name` for multi-client filtering

---

#### `PUT /api/admin/client-requests/:id`
**Auth**: Admin only
**Purpose**: Update request status and add admin notes

**Request**:
```json
{
  "status": "in_progress",
  "admin_notes": "Working on this, will deploy to testing on Friday"
}
```

**Response**:
```json
{
  "request": {
    "id": "uuid",
    "status": "in_progress",
    "admin_notes": "...",
    "updated_at": "2025-10-04T11:00:00Z"
  }
}
```

---

### Slide Template Management (MVP: Simple Upload)

**Architecture Decision**: Templates stored in S3, generated presentations stored in `conversation_sessions` table.

```
Storage:
  S3 Templates: s3://buzztrail-slide-templates/{template-name}/
    ├── slides.md              # Base Slidev markdown
    ├── metadata.json          # Slide annotations (budget ranges, keywords)
    └── assets/                # Images, videos, etc.

  Database: slide_templates table (simple metadata tracking)

  Generated: conversation_sessions.slidev_url (deployed presentation)
```

---

#### `GET /api/admin/slide-templates`
**Auth**: Admin only
**Purpose**: List all slide templates (scalable for thousands of customers)

**Query params**:
- `?status=active|archived|draft` - Filter by status
- `?customer_id=uuid` - Filter by customer (or "default" for shared templates)
- `?search=query` - Full-text search on template name/description
- `?sort=name|usage|updated` - Sort field
- `?order=asc|desc` - Sort order
- `?page=1&limit=50` - Pagination (default: 50 per page)

**Response**:
```json
{
  "templates": [
    {
      "id": "uuid",
      "template_id": "product-demo-v2",
      "template_name": "Product Demo V2",
      "customer_id": null,
      "customer_name": null,
      "description": "Standard SaaS product demo",
      "storage_path": "default/product-demo-v2",
      "version": 2,
      "status": "active",
      "total_slides": 12,
      "thumbnail_url": "https://cdn.buzztrail.ai/thumbnails/product-demo-v2.jpg",
      "usage_count": 1234,
      "associated_personas_count": 15,
      "last_used_at": "2025-10-08T14:22:00Z",
      "created_at": "2025-09-01T10:00:00Z",
      "updated_at": "2025-10-05T11:00:00Z"
    },
    {
      "id": "uuid2",
      "template_id": "custom-enterprise",
      "template_name": "Acme Corp Enterprise Demo",
      "customer_id": "cust-uuid",
      "customer_name": "Acme Corp",
      "description": "Custom demo with Acme branding",
      "storage_path": "customers/cust-uuid/custom-enterprise",
      "version": 1,
      "status": "active",
      "total_slides": 15,
      "thumbnail_url": "https://cdn.buzztrail.ai/thumbnails/cust-uuid/custom-enterprise.jpg",
      "usage_count": 47,
      "associated_personas_count": 3,
      "last_used_at": "2025-10-08T09:15:00Z",
      "created_at": "2025-09-15T11:00:00Z",
      "updated_at": "2025-09-20T14:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 847,
    "total_pages": 17
  },
  "summary": {
    "total_default_templates": 12,
    "total_customer_templates": 835,
    "total_customers_with_templates": 156
  }
}
```

---

#### `GET /api/admin/slide-templates/:id`
**Auth**: Admin only
**Purpose**: Get template details

**Response**:
```json
{
  "template": {
    "id": "uuid",
    "template_name": "saas-demo-v1",
    "description": "Standard SaaS product demo",
    "s3_folder_path": "s3://buzztrail-slide-templates/saas-demo-v1/",
    "version": 1,
    "status": "active",
    "metadata_preview": {
      "total_slides": 12,
      "slide_ids": ["intro", "problem", "solution", "pricing-startup", "pricing-enterprise"],
      "keywords": ["automation", "analytics", "pricing"],
      "budget_ranges": ["0-100k", "100k+"]
    },
    "created_at": "2025-09-01T10:00:00Z",
    "updated_at": "2025-09-01T10:00:00Z"
  }
}
```

---

#### `POST /api/admin/slide-templates/upload`
**Auth**: Admin only
**Purpose**: Upload new slide template to S3

**Request**: `multipart/form-data`
```
template_name: "saas-demo-v1"
description: "Standard SaaS product demo"
template_files: [zip file or folder structure]
```

**Backend logic**:
1. Extract uploaded files
2. Validate structure (slides.md exists, metadata.json valid)
3. Upload to S3: `s3://buzztrail-slide-templates/{template_name}/`
4. Insert into `slide_templates` table
5. Parse metadata.json and store preview

**Response**:
```json
{
  "template": {
    "id": "uuid",
    "template_name": "saas-demo-v1",
    "s3_folder_path": "s3://buzztrail-slide-templates/saas-demo-v1/",
    "status": "active",
    "created_at": "2025-10-06T10:00:00Z"
  }
}
```

---

#### `PUT /api/admin/slide-templates/:id`
**Auth**: Admin only
**Purpose**: Update template metadata or re-upload files

**Request**: `multipart/form-data` (optional file upload)
```
description: "Updated description"
status: "archived"
template_files: [optional: new zip file]
```

**Backend logic**:
1. Update `slide_templates` table
2. If files uploaded: increment version, upload to S3
3. Update `updated_at` timestamp

**Response**:
```json
{
  "template": {
    "id": "uuid",
    "template_name": "saas-demo-v1",
    "version": 2,
    "updated_at": "2025-10-06T11:00:00Z"
  }
}
```

---

#### `DELETE /api/admin/slide-templates/:id`
**Auth**: Admin only
**Purpose**: Archive template (soft delete)

**Validation**:
- Mark as archived (don't delete from S3)
- Still accessible for replay of existing presentations

**Response**:
```json
{
  "success": true,
  "template_id": "uuid",
  "status": "archived"
}
```

---

#### `POST /api/admin/slide-templates/:id/clone`
**Auth**: Admin only
**Purpose**: Clone template to multiple customers (bulk distribution)

**Request**:
```json
{
  "target_customer_ids": ["cust-uuid-1", "cust-uuid-2", "cust-uuid-3"],
  "options": {
    "create_as_draft": true,
    "auto_assign_personas": false,
    "persona_ids": []
  }
}
```

**Backend logic**:
1. Validate template exists and is active
2. For each customer_id:
   - Check if customer already has this template (skip if exists)
   - Copy template record with new customer_id
   - Copy storage files to customer-specific path
   - Optionally associate with customer personas
   - Set status to "draft" if requested
3. Track bulk operation progress
4. Return summary

**Response**:
```json
{
  "operation_id": "bulk-uuid",
  "templates_created": 3,
  "skipped": [],
  "errors": [],
  "storage_used_mb": 90,
  "summary": {
    "created_for_customers": [
      {
        "customer_id": "cust-uuid-1",
        "customer_name": "Acme Corp",
        "template_id": "uuid-new-1",
        "storage_path": "customers/cust-uuid-1/product-demo-v2"
      },
      {
        "customer_id": "cust-uuid-2",
        "customer_name": "Globex Inc",
        "template_id": "uuid-new-2",
        "storage_path": "customers/cust-uuid-2/product-demo-v2"
      }
    ]
  }
}
```

---

#### `GET /api/client/slide-templates`
**Auth**: Client only (RLS enforced)
**Purpose**: List templates available to this client (read-only)

**Query params**:
- `?persona_id=uuid` - Filter by associated persona

**Response**:
```json
{
  "templates": [
    {
      "id": "uuid",
      "template_name": "Product Demo V2",
      "description": "Standard product demo presentation",
      "total_slides": 12,
      "thumbnail_url": "https://cdn.buzztrail.ai/thumbnails/product-demo-v2.jpg",
      "usage_count": 47,
      "associated_personas": [
        {
          "id": "persona-uuid",
          "name": "Sales Demo Bot",
          "status": "production"
        }
      ],
      "last_used_at": "2025-10-08T14:22:00Z"
    }
  ]
}
```

---

#### `GET /api/client/slide-templates/:id`
**Auth**: Client only (RLS enforced)
**Purpose**: View template details with slide preview (read-only)

**Response**:
```json
{
  "template": {
    "id": "uuid",
    "template_name": "Product Demo V2",
    "description": "Standard product demo presentation",
    "total_slides": 12,
    "thumbnail_url": "https://cdn.buzztrail.ai/thumbnails/product-demo-v2.jpg",
    "slides_preview": [
      {
        "slide_number": 1,
        "slide_id": "intro",
        "title": "Introduction",
        "thumbnail_url": "https://cdn.buzztrail.ai/slides/product-demo-v2/01-intro.jpg"
      },
      {
        "slide_number": 2,
        "slide_id": "problem",
        "title": "The Problem",
        "thumbnail_url": "https://cdn.buzztrail.ai/slides/product-demo-v2/02-problem.jpg"
      }
    ],
    "associated_personas": [
      {
        "id": "persona-uuid",
        "name": "Sales Demo Bot"
      }
    ]
  }
}
```

---

#### `GET /api/sessions/:sessionId/presentation`
**Auth**: Admin or Client (via RLS)
**Purpose**: Get generated presentation for a session

**Response**:
```json
{
  "presentation": {
    "session_id": "uuid",
    "slidev_url": "https://slides.buzztrail.ai/s/k3j5-h2g9-f8d7",
    "template_used": "saas-demo-v1",
    "generated_at": "2025-10-06T12:30:00Z",
    "customization": {
      "slidesToShow": [
        {"slideId": "intro", "order": 1},
        {"slideId": "automation", "order": 2, "emphasize": true},
        {"slideId": "pricing-startup", "order": 3}
      ],
      "slidesToSkip": [
        {"slideId": "enterprise", "reason": "small team (50 employees)"},
        {"slideId": "pricing-enterprise", "reason": "budget $50k"}
      ],
      "contentReplacements": {
        "COMPANY_NAME": "Acme Corp",
        "CONTENT_PRICING": "Based on your budget of $50k..."
      }
    }
  }
}
```

**Note**: This returns data from `conversation_sessions` table (already generated during intermission), not the template itself.

---

### Future Iterations (Post-MVP)
- Template editor UI (edit slides.md and metadata.json in browser)
- Template versioning history
- Template cloning
- Visual slide preview/thumbnails
- Advanced customization rules editor
- A/B testing different templates

---

### Admin Client Management

#### `POST /api/admin/clients`
**Auth**: Admin only
**Purpose**: Create new client

**Request**:
```json
{
  "client_name": "Acme Corp",
  "tier": "growth",
  "contact_email": "admin@acme.com"
}
```

**Backend logic**:
1. Generate `client_id` (UUID)
2. Insert into `clients` table

**Response**:
```json
{
  "client": {
    "client_id": "uuid",
    "client_name": "Acme Corp",
    "tier": "growth",
    "contact_email": "admin@acme.com",
    "created_at": "2025-10-04T10:00:00Z"
  }
}
```

---

#### `GET /api/admin/clients`
**Auth**: Admin only
**Purpose**: List all clients

**Response**:
```json
{
  "clients": [
    {
      "client_id": "uuid",
      "client_name": "Acme Corp",
      "tier": "growth",
      "active_personas_count": 3,
      "total_sessions_count": 147,
      "last_activity_at": "2025-10-03T14:22:00Z"
    }
  ]
}
```

---

#### `GET /api/admin/clients/:id`
**Auth**: Admin only
**Purpose**: Get client details + usage

**Response**:
```json
{
  "client": {
    "client_id": "uuid",
    "client_name": "Acme Corp",
    "tier": "growth",
    "contact_email": "admin@acme.com",
    "created_at": "2025-09-01T10:00:00Z",

    // Usage stats
    "usage": {
      "personas": {
        "total": 3,
        "by_status": {
          "testing": 0,
          "staging": 1,
          "production": 2,
          "archived": 0
        }
      },
      "sessions": {
        "total": 147,
        "last_30_days": 42,
        "avg_duration_seconds": 890
      }
    }
  }
}
```

---

#### `PUT /api/admin/clients/:id`
**Auth**: Admin only
**Purpose**: Update client metadata

**Request**:
```json
{
  "client_name": "Acme Corporation",
  "tier": "premium",
  "contact_email": "newadmin@acme.com"
}
```

---

### Webhook Handlers (Supabase Edge Functions)

#### `POST /api/webhooks/tavus`
**Auth**: Tavus webhook signature validation (HMAC)
**Purpose**: Handle Tavus conversation events

**Events handled**:
- `conversation.started`
- `conversation.ended`
- `conversation.updated`

**Logic for `conversation.ended`**:
1. Validate Tavus HMAC signature
2. Extract transcript, objectives, shutdown_reason
3. Update `conversation_sessions` table (phase1 data)
4. Trigger Motia intermission workflow
5. Return 200 OK

---

#### `POST /api/webhooks/langfuse`
**Auth**: Langfuse webhook token validation
**Purpose**: Handle annotation status updates from Langfuse

**Events handled**:
- Annotation reviewed by admin in Langfuse
- Dataset created from annotations

**Logic**:
1. Validate Langfuse webhook token
2. Update `annotations` table status
3. Return 200 OK

---

## Database Schema Changes

### New Tables

#### `persona_version_history`
**Note**: This table is defined in `customer-persona-lifecycle-management.md` PRD. Schema uses simple integer version field.

```sql
-- Reference only - actual schema in customer-persona-lifecycle-management.md
CREATE TABLE persona_version_history (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  persona_id uuid NOT NULL REFERENCES client_personas(id) ON DELETE CASCADE,
  version integer NOT NULL,
  changed_by uuid NOT NULL REFERENCES auth.users(id),
  changed_fields jsonb,
  diff jsonb,
  created_at timestamptz DEFAULT now()
);
```

#### `slidev_templates` (Scalable Multi-Tenant Template System)
**Scalable approach**: Supports thousands of customers with customer-specific and default templates.

```sql
CREATE TABLE slidev_templates (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Identity & Organization
  template_id TEXT NOT NULL,              -- e.g., "product-demo-v2"
  template_name TEXT NOT NULL,            -- Display name
  customer_id TEXT,                       -- NULL = default template (available to all)
  description TEXT,

  -- Storage (see slidev-control-mvp PRD for path structure)
  storage_path TEXT NOT NULL,             -- e.g., "default/starter" or "customers/{customer_id}/product-demo"

  -- Versioning
  version INTEGER DEFAULT 1,

  -- Metadata
  total_slides INTEGER DEFAULT 0,
  thumbnail_url TEXT,                     -- Preview image

  -- Analytics
  usage_count INTEGER DEFAULT 0,          -- Total presentations generated
  associated_personas_count INTEGER DEFAULT 0,

  -- Status
  status TEXT NOT NULL DEFAULT 'active',  -- 'draft' | 'active' | 'archived'

  -- Timestamps
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  created_by UUID REFERENCES auth.users(id),

  UNIQUE(customer_id, template_id, version)
);

-- Indexes for scale (thousands of customers × dozens of templates)
CREATE INDEX idx_templates_customer ON slidev_templates(customer_id, status);
CREATE INDEX idx_templates_status ON slidev_templates(status) WHERE status = 'active';
CREATE INDEX idx_templates_usage ON slidev_templates(usage_count DESC);
CREATE INDEX idx_templates_search ON slidev_templates USING gin(to_tsvector('english', template_name || ' ' || COALESCE(description, '')));

-- RLS Policies
ALTER TABLE slidev_templates ENABLE ROW LEVEL SECURITY;

-- Admins can manage all templates
CREATE POLICY "Admins manage slide templates"
  ON slidev_templates FOR ALL
  USING (auth.jwt() ->> 'role' = 'admin');

-- Clients can view their templates + default templates (read-only)
CREATE POLICY "Clients view own and default templates"
  ON slidev_templates FOR SELECT
  USING (
    status = 'active' AND (
      customer_id IS NULL OR  -- default templates
      customer_id = auth.jwt() ->> 'customer_id'  -- their templates
    )
  );
```

**Presentation Storage**: Generated presentations stored in `conversation_sessions` table:
- `conversation_sessions.slidev_url` - Unique URL for deployed presentation (1:1 with session)
- `conversation_sessions.slidev_deck_id` - Unique deck ID (xxxx-xxxx-xxxx format)
- `conversation_sessions.slidev_template_id` - References slidev_templates(id)
- `conversation_sessions.slidev_data` - JSONB with placeholder data used
- `conversation_sessions.slide_customization` - JSONB with customization plan
- `conversation_sessions.slidev_generated_at` - Timestamp

**Key Scalability Features**:
- **Multi-tenancy**: `customer_id` column enables customer-specific templates
- **Full-text search**: GIN index on name+description for fast searching
- **Usage tracking**: `usage_count` for analytics without counting session rows
- **Hierarchical organization**: NULL customer_id = default (shared), non-NULL = customer-specific
- **RLS policies**: Clients see only their templates + defaults, admins see all

### Schema Updates

**Note**: Version field and auto-increment trigger are defined in `customer-persona-lifecycle-management.md` PRD.

#### Key Points for API Implementation:
- `client_personas.version` is an integer (not semantic version string)
- `slidev_templates.version` is an integer (incremented when template re-uploaded)
- Database trigger `log_persona_version_change()` auto-increments on ANY update
- API should read `version` as integer, display as "v{version}" in UI (e.g., version 12 → "v12")
- Version history stored in `persona_version_history` table with integer version field
- Generated presentations stored in `conversation_sessions` (not separate table)
- Template uniqueness: `(customer_id, template_id, version)` allows same template_id across customers
- Query optimization: Use indexes for customer filtering, status filtering, and full-text search

---

## Tech Stack

### Backend Framework
- **Node.js 18+** with **TypeScript**
- **Hono** (fast, lightweight Express alternative) or **Fastify**
- **Supabase JS Client** for database access

### Deployment
- **Vercel** (recommended - easy deploy, edge functions support)
- Or **Nx.dev** monorepo with `apps/api` application

### Dependencies
```json
{
  "dependencies": {
    "@supabase/supabase-js": "^2.x",
    "hono": "^3.x",
    "zod": "^3.x",
    "jose": "^5.x"
  }
}
```

---

## Security

### JWT Validation
Every request validates Supabase JWT:
```typescript
import { createClient } from '@supabase/supabase-js';
import { jwtVerify } from 'jose';

async function validateRequest(req: Request) {
  const token = req.headers.get('Authorization')?.replace('Bearer ', '');
  if (!token) throw new Error('Unauthorized');

  // Verify JWT
  const { payload } = await jwtVerify(token, SUPABASE_JWT_SECRET);

  return {
    user_id: payload.sub,
    role: payload.role,
    client_id: payload.user_metadata?.client_id
  };
}
```

### RLS Enforcement
Backend uses authenticated Supabase client (with user's JWT), not service role:
```typescript
// CORRECT: Uses user's JWT, RLS enforced
const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  global: {
    headers: {
      Authorization: `Bearer ${userJwt}`
    }
  }
});

// WRONG: Service role bypasses RLS (only for admin endpoints)
const supabaseAdmin = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
```

---

## Decisions Made

### 1. Tavus Sync Strategy
**Decision**: ✅ Automatic sync on persona access (no manual button needed)

**Implementation**:
- On `GET /api/personas/:id` → Check `last_synced_at` timestamp
- If > 5 minutes ago: Fetch from Tavus, compare, update DB if changed
- If changed: Database trigger increments version by 1
- Return updated persona

**Alternative** (Phase 2): Background job every 15 minutes syncs all personas

**Rationale**: Simple, ensures UI always shows latest without manual intervention

### 2. Client Voice Changes
**Decision**: ❌ REMOVED - Clients cannot change voice
- Voice is read-only in client UI (display only)
- Clients must submit form request for voice changes
- Admin reviews request, changes voice in Tavus UI
- Backend auto-syncs changes on next persona access

### 3. Version Increments
**Decision**: ✅ Simple auto-increment (v1, v2, v3, etc.)
- ANY change to persona increments version by 1
- No semantic versioning (major.minor.patch)
- Database trigger handles all version increments automatically

### 4. Langfuse Integration Scope
**Decision**: ✅ One-way POST (Simple)
- POST annotations to Langfuse when created
- Store `langfuse_trace_id` in our database
- No feedback loop back from Langfuse to our system
- Admins can view/analyze in Langfuse dashboard directly

**Implementation**:
```typescript
// When annotation is submitted
POST https://cloud.langfuse.com/api/public/traces
{
  "name": "conversation_annotation",
  "metadata": {
    "session_id": "uuid",
    "client_id": "uuid",
    "category": "behavior_issue",
    "severity": "medium"
  }
}
```

### 5. Error Handling for Tavus Sync
**Decision**: Fail immediately (return error to admin), log for monitoring
- Admin can retry manually
- Future: Add retry queue if failures become common

---

## Out of Scope (Separate PRDs)

- ❌ **Recording playback** → `recording-playback-system.md`
- ❌ **Email notifications** → Future enhancement
- ❌ **Export (CSV/JSON)** → Future enhancement
- ❌ **Real-time updates (WebSockets)** → Removed entirely
- ❌ **Analytics dashboards** → Future enhancement
- ❌ **Live session monitoring** → Removed entirely

---

## Implementation Plan

### Week 1: Setup & Auth
- [ ] Initialize Hono/Fastify API project in Nx
- [ ] Set up Supabase client with JWT validation
- [ ] Implement auth middleware (role extraction)
- [ ] Create RLS test suite

### Week 2: Persona APIs
- [ ] `GET /api/personas` (client + admin filtering)
- [ ] `GET /api/personas/:id`
- [ ] `PUT /api/personas/:id/settings`
- [ ] Auto-version trigger and history table
- [ ] Test version increments

### Week 3: Tavus Sync & Admin
- [ ] `POST /api/admin/personas/:id/sync-from-tavus`
- [ ] Tavus API integration (fetch persona)
- [ ] Diff detection and version bump logic
- [ ] `GET /api/personas/:id/versions`

### Week 4: Session & Slide Deck APIs
- [ ] `GET /api/sessions`
- [ ] `GET /api/sessions/:id`
- [ ] `GET /api/sessions/:id/transcript`
- [ ] `GET /api/sessions/:id/recordings` (list only, no URLs)
- [ ] `GET /api/sessions/:id/slides` (slide metadata for session)
- [ ] `GET/POST/PUT/DELETE /api/admin/slide-decks`
- [ ] `GET /api/slide-decks/:id` (client + admin access)
- [ ] `GET /api/slide-decks/:id/versions`

### Week 5: Slide Management & Annotations
- [ ] `GET /api/slide-decks/:id/slides`
- [ ] `PUT /api/admin/slide-decks/:id/slides/:slideId`
- [ ] `POST /api/admin/slide-decks/:id/slides/reorder`
- [ ] `GET/PUT /api/slide-decks/:id/rules` (customization rules)
- [ ] `GET /api/slide-decks/:id/analytics`
- [ ] `POST /api/annotations`
- [ ] Langfuse integration (POST trace)
- [ ] `GET /api/sessions/:id/annotations`
- [ ] `POST /api/client-requests`
- [ ] `GET /api/client-requests`

### Week 6: Admin & Webhooks
- [ ] `GET/POST/PUT /api/admin/clients`
- [ ] `PUT /api/admin/client-requests/:id`
- [ ] `POST /api/webhooks/tavus` (Edge Function)
- [ ] `POST /api/webhooks/langfuse` (Edge Function)
- [ ] Full E2E testing

---

**Status**: Draft
**Next Steps**: Review open questions, decide on Tavus sync strategy, begin Week 1 implementation
