{"openapi":"3.0.0","info":{"title":"TCM Backend API","version":"1.0.0","description":"\n# 🎯 TCM Platform Backend API\n\nA comprehensive learning management and social platform built with enterprise-grade architecture using Bun, Hono, and Drizzle.\n\n## 🏗️ Enterprise Architecture\n- **Controllers**: Clean separation of HTTP request handling  \n- **Services**: Business logic layer with proper abstraction\n- **Validation**: Input validation with comprehensive error handling\n- **Error Management**: Standardized error responses with codes\n- **Performance**: Optimized queries and pagination limits\n\n## 🔐 Authentication\n\n### User Authentication (Frontend Apps)\nAll `/api/*` endpoints require a valid **Clerk JWT token** in the Authorization header:\n```\nAuthorization: Bearer YOUR_JWT_TOKEN\n```\n\n### Admin Dashboard Authentication  \nAdmin dashboard routes (`/api/admin/*`) use **Clerk JWT + Organization Verification**:\n```\nAuthorization: Bearer YOUR_JWT_TOKEN\nX-Require-Org: true\n```\n\nSetting `X-Require-Org: true` enforces organization membership check. If `CLERK_REQUIRED_ORG_ID` is configured, only users in that organization can access admin endpoints.\n\n### Public Endpoints\nThe following endpoints do NOT require authentication:\n- System endpoints (`/health`, `/`)\n- Video processing endpoints (`/video/*`) - Public access for uploads and processing\n- Webhook endpoints (`/webhook/*`) - External service integration\n- Inngest automation endpoints (`/automations/*`) - Self-authenticated\n\n**Key Differences:**\n- **User Routes** (`/api/users/*`, `/api/stripe/*`, etc.): Use Clerk JWT tokens, user-specific permissions\n- **Admin Routes** (`/api/admin/*`): Use Clerk JWT + `X-Require-Org` header for org verification\n- **Video Routes** (`/video/*`): Public access, no authentication required\n- **System Routes**: Public health checks and API information\n\n### Admin Endpoints Available:\n**Dashboard:**\n- `GET /api/admin/dashboard/stats` - Platform statistics\n- `GET /api/admin/dashboard/subcount` - Active subscriptions count (⚡ cached 30s)\n- `GET /api/admin/dashboard/cache-stats` - Cache performance metrics\n- `POST /api/admin/dashboard/clear-cache` - Clear cache entries\n\n**User Management:**\n- `GET /api/admin/users` - List all users (paginated)\n- `GET /api/admin/users/:id` - Get user by ID\n- `POST /api/admin/users` - Create new user\n- `PATCH /api/admin/users/:id` - Update user\n- `DELETE /api/admin/users/:id` - Delete user\n\n**Forms Management:**\n- `GET /api/admin/forms` - List all forms\n- `GET /api/admin/forms/:id` - Get form by ID\n- `GET /api/admin/forms/:id/submissions` - Get form submissions\n- `POST /api/admin/forms` - Create new form\n- `PATCH /api/admin/forms/:id` - Update form\n- `DELETE /api/admin/forms/:id` - Delete form\n\n**Security Note**: Admin endpoints verify both JWT validity and organization membership for enhanced security.\n\n## 📱 Features\n- **User Management** - Complete user profiles with membership levels\n- **Learning Platform** - Courses, lessons, and progress tracking  \n- **Social Features** - Posts, comments, likes, and follows\n- **Admin Tools** - Comprehensive admin controls via service account\n- **Video Processing** - Public video processing APIs with automated transcoding\n\n## 🎬 Video Processing System\nThe platform includes a comprehensive video processing system powered by AWS MediaConvert and Inngest automation:\n\n### Key Features:\n- **Multi-Quality Support**: 720p, 1080p, 2K, 4K transcoding\n- **Cost Control**: Quality-based cost estimation and warnings\n- **Entity Support**: Videos for lessons, courses, and builder content blocks\n- **Automation**: Inngest-powered workflow with status tracking\n- **S3 Integration**: Direct upload with CloudFront delivery\n- **Error Handling**: Comprehensive failure detection and retry logic\n- **Public API**: No authentication required for video operations\n\n### Processing Workflow:\n1. **Upload**: Generate presigned S3 URL for direct upload\n2. **Processing**: Trigger MediaConvert job with selected qualities\n3. **Monitoring**: Inngest tracks progress with automatic retries\n4. **Completion**: Database updated with processed video URLs\n5. **Delivery**: Videos served via CloudFront CDN\n\n### Cost Estimates (per 10-minute video):\n- **720p**: ~$0.15 (1.2x processing time)\n- **1080p**: ~$0.30 (1.5x processing time)\n- **2K**: ~$0.60 (2x processing time)\n- **4K**: ~$1.20 (3x processing time)\n\n## 🚀 Error Handling\nAll endpoints return standardized error responses:\n- **400**: Validation errors with detailed messages\n- **401**: Authentication failures (missing/invalid tokens or API keys)\n- **403**: Insufficient privileges (non-admin users accessing admin routes)\n- **404**: Resource not found with specific identifiers  \n- **500**: Database/server errors with operation context\n- **Error Codes**: `VALIDATION_ERROR`, `NOT_FOUND`, `DATABASE_ERROR`, `MISSING_AUTH_HEADER`, `INVALID_ADMIN_API_KEY`\n\n## ⚡ Performance Optimizations\n\n### JWT Verification Caching (3-Layer Strategy)\n**Layer 1: Networkless Verification** (if `CLERK_JWT_KEY` is set)\n- Uses PEM public key for local signature verification\n- **No external API calls** to Clerk\n- ~50-80ms verification time\n\n**Layer 2: JWT Payload Caching** (always enabled)\n- Caches verified JWT payload for **50 minutes** (3000s)\n- Cache key: Last 32 characters of token\n- **First verification**: 50-800ms (depending on networkless vs API)\n- **Cached hits**: ~5-10ms (95%+ faster! ⚡)\n- TTL: 50min is safe since Clerk JWTs expire in 1 hour\n\n**Layer 3: Clerk's Internal JWKS Caching** (automatic)\n- Clerk SDK caches public keys internally\n- You don't need to configure this (formerly `jwksCacheTtlInMs`)\n\n**Performance Impact:**\n- Without `CLERK_JWT_KEY`: 800ms → 5ms (99% faster on cache hit)\n- With `CLERK_JWT_KEY`: 80ms → 5ms (94% faster on cache hit)\n\n### Query Result Caching\nFrequently accessed data is cached for **30 seconds**:\n- Active subscriptions count: 30s TTL\n- Dashboard statistics: Real-time (no cache)\n- Cache hit ratio visible via `/api/admin/dashboard/cache-stats`\n\nAll cached responses include `fromCache: true/false` to indicate cache hit.\n\n### Expected Performance (with optimizations)\n- **Dashboard stats**: 0.2-0.3s (first) → 0.05s (cached)\n- **Subscription count (cached)**: 0.3s → 0.05s (⚡ 85% faster)\n- **User list**: 0.2-0.4s\n- **Forms list**: 0.2-0.4s\n- **Auth overhead**: 800ms → 5ms (⚡ 99% faster with cache)\n\n## 🌟 Built With\n- **Runtime**: Bun\n- **Framework**: Hono  \n- **Database**: PostgreSQL + Drizzle ORM\n- **Authentication**: Clerk JWT (with org verification)\n- **Caching**: In-memory (JWT + query results)\n- **Security**: ArcJet protection + CORS\n- **Logging**: Winston with structured logs\n- **Video Processing**: AWS MediaConvert + S3 + CloudFront\n- **Automation**: Inngest workflows\n- **Architecture**: Controllers → Services → Database\n\n## 🚀 Getting Started\nVisit the [Frontend Integration Guide](./frontend-guide) for React/Next.js examples.\n    ","contact":{"name":"TCM Platform","url":"https://tcm.com"}},"servers":[{"url":"http://localhost:3000","description":"Development server"},{"url":"https://api.tcm.com","description":"Production server"}],"security":[{"BearerAuth":[]}],"components":{"schemas":{"User":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique user identifier"},"createdAt":{"type":"string","format":"date-time","description":"Account creation timestamp"},"clerkId":{"type":"string","nullable":true,"description":"Clerk authentication ID"},"email":{"type":"string","format":"email","nullable":true,"description":"User email address"},"firstName":{"type":"string","nullable":true,"description":"First name"},"lastName":{"type":"string","nullable":true,"description":"Last name"},"name":{"type":"string","nullable":true,"description":"Full display name"},"username":{"type":"string","nullable":true,"description":"Unique username"},"avatarUrl":{"type":"string","format":"uri","nullable":true,"description":"Profile picture URL"},"bio":{"type":"string","nullable":true,"description":"User biography"},"website":{"type":"string","format":"uri","nullable":true,"description":"Personal website URL"},"phone":{"type":"string","nullable":true,"description":"Phone number"},"isAdmin":{"type":"boolean","default":false,"description":"Admin privileges"},"isVerified":{"type":"boolean","default":false,"description":"Account verification status"},"darkMode":{"type":"boolean","default":false,"description":"Dark mode preference"},"membershipType":{"type":"string","enum":["web","app"],"nullable":true,"description":"Type of membership"},"memberships":{"type":"array","items":{"type":"string","enum":["coachapp_membership","accreditation","nlp","ultimate_launch","holistic_modalities","crt","course_creator","exponential_growth","full_access","accelerate","livestream","business_mastery"]},"nullable":true,"description":"Array of user memberships"},"membershipCallBooked":{"type":"boolean","nullable":true,"description":"Whether membership call is booked"},"unreadNotifications":{"type":"integer","default":0,"description":"Number of unread notifications"},"onboardingStep":{"type":"integer","nullable":true,"description":"Current onboarding step"},"wpUserId":{"type":"string","nullable":true,"description":"WordPress user ID"},"oldUserId":{"type":"string","nullable":true,"description":"Legacy user ID"},"streamToken":{"type":"string","nullable":true,"description":"Stream chat token"},"pwRefreshed":{"type":"boolean","default":false,"description":"Password refresh status"},"metadata":{"type":"object","additionalProperties":true,"nullable":true,"description":"Additional user metadata"},"updatedAt":{"type":"string","format":"date-time","nullable":true,"description":"Last update timestamp"}},"required":["id","createdAt"]},"Category":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique category identifier"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"name":{"type":"string","description":"Category name"},"description":{"type":"string","nullable":true,"description":"Category description"}},"required":["id","createdAt","name"]},"Course":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique course identifier"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","nullable":true,"description":"Last update timestamp"},"title":{"type":"string","nullable":true,"description":"Course title"},"description":{"type":"string","nullable":true,"description":"Course description"},"level":{"type":"string","nullable":true,"description":"Difficulty level"},"studyType":{"type":"string","nullable":true,"description":"Type of study"},"totalDuration":{"type":"string","nullable":true,"description":"Total course duration"},"logo":{"type":"string","format":"uri","nullable":true,"description":"Course logo URL"},"thumbnailUrl":{"type":"string","format":"uri","nullable":true,"description":"Thumbnail image URL"},"demoVideoUrl":{"type":"string","format":"uri","nullable":true,"description":"Demo video URL"},"promotionalVideoUrl":{"type":"string","format":"uri","nullable":true,"description":"Promotional video URL"},"categoryId":{"type":"string","format":"uuid","nullable":true,"description":"Associated category ID"},"isHidden":{"type":"boolean","default":false,"description":"Whether course is hidden"},"isPremium":{"type":"boolean","nullable":true,"description":"Whether course requires premium access"},"wpId":{"type":"integer","description":"WordPress post ID"}},"required":["id","createdAt","wpId"]},"Lesson":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique lesson identifier"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"title":{"type":"string","nullable":true,"description":"Lesson title"},"description":{"type":"string","nullable":true,"description":"Lesson description"},"content":{"type":"string","nullable":true,"description":"Lesson content"},"videoUrl":{"type":"string","format":"uri","nullable":true,"description":"Video URL"},"duration":{"type":"string","nullable":true,"description":"Lesson duration"},"courseId":{"type":"string","format":"uuid","nullable":true,"description":"Associated course ID"},"isPremium":{"type":"boolean","default":false,"description":"Whether lesson requires premium access"},"isHidden":{"type":"boolean","default":false,"description":"Whether lesson is hidden"},"order":{"type":"integer","nullable":true,"description":"Lesson order within course"},"wpId":{"type":"integer","nullable":true,"description":"WordPress post ID"}},"required":["id","createdAt"]},"UserProgress":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique progress record identifier"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","description":"Last update timestamp"},"userId":{"type":"string","format":"uuid","description":"User ID"},"courseId":{"type":"string","format":"uuid","nullable":true,"description":"Course ID"},"lessonId":{"type":"string","format":"uuid","nullable":true,"description":"Lesson ID"},"isCompleted":{"type":"boolean","default":false,"description":"Whether item is completed"},"progressPercentage":{"type":"integer","default":0,"description":"Progress percentage (0-100)"},"watchedDuration":{"type":"integer","default":0,"description":"Watched duration in seconds"},"startedAt":{"type":"string","format":"date-time","nullable":true,"description":"When user started"},"completedAt":{"type":"string","format":"date-time","nullable":true,"description":"When user completed"}},"required":["id","createdAt","updatedAt","userId"]},"Post":{"type":"object","properties":{"id":{"type":"string","format":"uuid","description":"Unique post identifier"},"createdAt":{"type":"string","format":"date-time","description":"Creation timestamp"},"updatedAt":{"type":"string","format":"date-time","nullable":true,"description":"Last update timestamp"},"body":{"type":"string","nullable":true,"description":"Post content"},"mediaUrl":{"type":"string","format":"uri","nullable":true,"description":"Media URL"},"mediaType":{"type":"string","nullable":true,"description":"Media type"},"userId":{"type":"string","format":"uuid","description":"Author user ID"},"likesCount":{"type":"integer","default":0,"description":"Number of likes"},"commentsCount":{"type":"integer","default":0,"description":"Number of comments"},"hotness":{"type":"number","format":"float","default":0,"description":"Post hotness score"}},"required":["id","createdAt","userId"]},"Error":{"type":"object","properties":{"error":{"type":"string","description":"Error message","example":"Video processing failed"},"message":{"type":"string","description":"Additional error details","example":"FFmpeg process failed with code 1"}},"required":["error"]},"HealthResponse":{"type":"object","properties":{"status":{"type":"string","enum":["ok","error"],"description":"Overall system status"},"environment":{"type":"string","description":"Current environment"},"database":{"type":"string","enum":["connected","disconnected"],"description":"Database connection status"},"supabase":{"type":"string","enum":["connected","disconnected"],"description":"Supabase connection status"},"timestamp":{"type":"string","format":"date-time","description":"Health check timestamp"}},"required":["status","environment","database","supabase","timestamp"]},"PaginationInfo":{"type":"object","properties":{"page":{"type":"integer","minimum":1,"description":"Current page number"},"limit":{"type":"integer","minimum":1,"maximum":100,"description":"Items per page"},"total":{"type":"integer","minimum":0,"description":"Total number of items"},"totalPages":{"type":"integer","minimum":0,"description":"Total number of pages"},"hasNext":{"type":"boolean","description":"Whether there is a next page"},"hasPrev":{"type":"boolean","description":"Whether there is a previous page"}},"required":["page","limit","total","totalPages","hasNext","hasPrev"]},"VideoQuality":{"type":"string","enum":["540p","720p","1080p","2k","4k"],"description":"Available video quality options"},"VideoQualityOption":{"type":"object","properties":{"id":{"type":"string","example":"720p"},"name":{"type":"string","example":"720P"},"width":{"type":"integer","example":1280},"height":{"type":"integer","example":720},"bitrate":{"type":"integer","example":5000000},"preset":{"type":"string","nullable":true},"recommended":{"type":"boolean","example":true}}},"CostEstimate":{"type":"object","properties":{"estimatedMinutes":{"type":"integer","example":15},"estimatedCost":{"type":"number","format":"float","example":0.45},"breakdown":{"type":"object","additionalProperties":{"type":"object","properties":{"minutes":{"type":"number","example":12},"cost":{"type":"number","format":"float","example":0.15}}}}}},"QualityValidation":{"type":"object","properties":{"isValid":{"type":"boolean","example":true},"errors":{"type":"array","items":{"type":"string"},"example":[]},"warnings":{"type":"array","items":{"type":"string"},"example":["High-quality options will increase processing costs"]}}},"UploadUrlRequest":{"type":"object","required":["fileName","contentType","entityType","entityId"],"properties":{"fileName":{"type":"string","example":"lesson-intro.mp4","description":"Original filename of the video"},"contentType":{"type":"string","example":"video/mp4","description":"MIME type of the video file"},"entityType":{"type":"string","enum":["lesson","course","builder"],"description":"Type of entity the video belongs to"},"entityId":{"type":"string","format":"uuid","description":"UUID of the lesson, course, or builder content"},"blockId":{"type":"string","description":"Block ID for builder content (required for builder type)"},"metadata":{"type":"object","additionalProperties":{"type":"string"},"description":"Additional metadata for the upload"}}},"UploadUrlResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"uploadUrl":{"type":"string","format":"uri","description":"Presigned S3 URL for direct upload"},"fileKey":{"type":"string","example":"lessons/123/video-intro-1642681234567.mp4","description":"S3 object key for the uploaded file"},"fileUrl":{"type":"string","format":"uri","description":"CloudFront URL for accessing the uploaded file"},"expiresIn":{"type":"integer","example":3600,"description":"URL expiration time in seconds"}}},"ProcessVideoRequest":{"type":"object","required":["entityType","entityId","sourceFileKey","sourceFileUrl","qualities"],"properties":{"entityType":{"type":"string","enum":["lesson","course","builder"]},"entityId":{"type":"string","format":"uuid"},"blockId":{"type":"string","description":"Required for builder content"},"sourceFileKey":{"type":"string","description":"S3 key of the uploaded source file"},"sourceFileUrl":{"type":"string","format":"uri","description":"URL of the uploaded source file"},"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"},"minItems":1,"description":"Selected quality options for processing"},"metadata":{"type":"object","additionalProperties":{"type":"string"},"description":"Additional processing metadata"}}},"ProcessVideoResponse":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Video processing started"},"entityType":{"type":"string","example":"lesson"},"entityId":{"type":"string","format":"uuid"},"blockId":{"type":"string"},"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"}},"estimate":{"$ref":"#/components/schemas/CostEstimate"},"warnings":{"type":"array","items":{"type":"string"}}}},"AcuityWebhookSuccessResponse":{"type":"object","properties":{"message":{"type":"string","description":"Success message with appointment ID","example":"Successfully processed appointment 1482410705"},"appointmentId":{"type":"integer","description":"The processed Acuity appointment ID","example":1482410705}},"required":["message","appointmentId"]},"AcuityWebhookErrorResponse":{"type":"object","properties":{"error":{"type":"string","description":"Error message describing what went wrong","example":"No appointment ID found in webhook body"},"code":{"type":"string","description":"Error code for programmatic handling","example":"MISSING_APPOINTMENT_ID","enum":["MISSING_APPOINTMENT_ID","APPOINTMENT_FETCH_FAILED","DATABASE_STORE_FAILED","UNKNOWN_ERROR"]},"appointmentId":{"type":"integer","description":"The appointment ID if available","example":1482410705,"nullable":true}},"required":["error","code"]},"StripeWebhookEvent":{"type":"object","properties":{"id":{"type":"string","description":"Unique identifier for the event","example":"evt_1234567890"},"object":{"type":"string","enum":["event"],"description":"String representing the object's type"},"created":{"type":"integer","description":"Time at which the object was created (Unix timestamp)","example":1326853478},"data":{"type":"object","properties":{"object":{"type":"object","description":"Object containing the event data","additionalProperties":true}},"description":"Object containing data associated with the event"},"livemode":{"type":"boolean","description":"Whether the event occurred in live mode or test mode","example":false},"pending_webhooks":{"type":"integer","description":"Number of webhooks that have not been successfully delivered","example":1},"request":{"type":"object","properties":{"id":{"type":"string","description":"ID of the API request that caused the event","example":"req_1234567890","nullable":true},"idempotency_key":{"type":"string","description":"Idempotency key of the request that caused the event","nullable":true}},"description":"Information on the API request that instigated the event"},"type":{"type":"string","description":"Description of the event type","enum":["payment_intent.created","payment_intent.succeeded","payment_intent.payment_failed","customer.created","customer.updated","invoice.payment_succeeded","invoice.payment_failed"],"example":"payment_intent.succeeded"}},"required":["id","object","created","data","livemode","pending_webhooks","type"]},"StripeWebhookSuccessResponse":{"type":"object","properties":{"message":{"type":"string","description":"Success message confirming webhook processing","example":"Webhook processed successfully"}},"required":["message"]},"StripeWebhookErrorResponse":{"type":"object","properties":{"error":{"type":"string","description":"Error message describing what went wrong","example":"Webhook signature verification failed"},"code":{"type":"string","description":"Error code for programmatic handling","example":"WEBHOOK_VERIFICATION_FAILED","enum":["WEBHOOK_VERIFICATION_FAILED","EVENT_PROCESSING_FAILED","INTERNAL_SERVER_ERROR"]}},"required":["error","code"]},"AutomationExecutionResult":{"type":"object","properties":{"functionId":{"type":"string","example":"ads-migrate"},"success":{"type":"boolean","example":true},"executionTime":{"type":"number","example":1250},"dataProcessed":{"type":"number","example":45},"errors":{"type":"array","items":{"type":"string"},"example":[]},"metadata":{"type":"object","properties":{"metaAdsCount":{"type":"number","example":12},"googleAdsCount":{"type":"number","example":8},"totalSpend":{"type":"number","example":1245.67},"conversions":{"type":"number","example":23}}}}},"CronSchedule":{"type":"object","properties":{"schedule":{"type":"string","example":"0 * * * *"},"description":{"type":"string","example":"Every hour"},"nextRun":{"type":"string","format":"date-time"},"functionName":{"type":"string","example":"ads-migrate"},"enabled":{"type":"boolean","example":true}}},"FFmpegVideoQuality":{"type":"string","enum":["540p","720p","1080p"],"description":"Available video quality options for FFmpeg processing"},"QualityConfig":{"type":"object","properties":{"resolution":{"type":"string","example":"1280x720"},"videoBitrate":{"type":"string","example":"3500k"},"maxBitrate":{"type":"string","example":"3500k"},"bufsize":{"type":"string","example":"7000k"}},"required":["resolution","videoBitrate","maxBitrate","bufsize"]},"QualityConfigs":{"type":"object","properties":{"540p":{"$ref":"#/components/schemas/QualityConfig"},"720p":{"$ref":"#/components/schemas/QualityConfig"},"1080p":{"$ref":"#/components/schemas/QualityConfig"}}},"FFmpegProgressUpdate":{"type":"object","properties":{"stage":{"type":"string","enum":["downloading","processing","uploading","completed","error"],"description":"Current stage of video processing","example":"processing"},"progress":{"type":"integer","minimum":0,"maximum":100,"description":"Progress percentage (0-100)","example":65},"message":{"type":"string","description":"Human-readable progress message","example":"Processing 720p: 45%"},"quality":{"$ref":"#/components/schemas/FFmpegVideoQuality","description":"Current quality being processed (if applicable)"},"currentQuality":{"type":"integer","minimum":1,"description":"Index of current quality being processed","example":2},"totalQualities":{"type":"integer","minimum":1,"description":"Total number of qualities to process","example":3},"details":{"type":"object","description":"Additional details about the progress","additionalProperties":true,"example":{"size":52428800}}},"required":["stage","progress","message"]},"FFmpegQualityOutput":{"type":"object","properties":{"quality":{"$ref":"#/components/schemas/FFmpegVideoQuality","description":"Video quality of this output"},"hlsUrl":{"type":"string","format":"uri","description":"Public URL of the HLS playlist file (.m3u8)","example":"https://your-supabase-url.supabase.co/storage/v1/object/public/hls/my-video-720p.m3u8"},"segmentCount":{"type":"integer","minimum":1,"description":"Number of HLS segments generated","example":15}},"required":["quality","hlsUrl","segmentCount"]},"FFmpegProcessingResult":{"type":"object","properties":{"success":{"type":"boolean","description":"Whether the processing was successful","example":true},"message":{"type":"string","description":"Human-readable result message","example":"Video successfully processed to HLS format in 3 qualities"},"outputs":{"type":"array","items":{"$ref":"#/components/schemas/FFmpegQualityOutput"},"description":"Array of processed quality outputs (only if successful)"},"totalQualities":{"type":"integer","minimum":0,"description":"Total number of qualities processed","example":3},"sessionId":{"type":"string","description":"Session ID used for progress tracking","example":"session_1640995200000_abc123def"},"error":{"type":"string","description":"Error message (only if failed)","example":"FFmpeg process failed with code 1"}},"required":["success"]},"FFmpegUrlProcessingRequest":{"type":"object","properties":{"videoUrl":{"type":"string","format":"uri","description":"URL of the video to download and process","example":"https://example.com/video.mp4"},"sessionId":{"type":"string","description":"Unique session ID for progress tracking via SSE","example":"session_1640995200000_abc123def"},"outputFileName":{"type":"string","description":"Custom output filename (optional)","example":"my-video"},"qualities":{"type":"array","items":{"$ref":"#/components/schemas/FFmpegVideoQuality"},"description":"Array of qualities to generate (defaults to all if not specified)","example":["1080p","720p"]}},"required":["videoUrl"]},"ValidationError":{"type":"object","properties":{"error":{"type":"string","example":"Validation failed"},"details":{"type":"array","items":{"type":"object","properties":{"code":{"type":"string","example":"invalid_string"},"message":{"type":"string","example":"Invalid video URL"},"path":{"type":"array","items":{"type":"string"},"example":["videoUrl"]}}}}},"required":["error","details"]}},"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Clerk JWT token for user authentication"},"AdminApiKey":{"type":"apiKey","in":"header","name":"X-Admin-API-Key","description":"Admin API key for dashboard service account access"}}},"paths":{"/":{"get":{"tags":["System"],"summary":"API Information","description":"Get basic API information and available endpoints","security":[],"responses":{"200":{"description":"API information","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"TCM Backend API"},"version":{"type":"string","example":"1.0.0"},"environment":{"type":"string","example":"development"},"documentation":{"type":"string","example":"/docs"},"authentication":{"type":"string","example":"Bearer token required for /api/* endpoints"}}}}}}}}},"/health":{"get":{"tags":["System"],"summary":"Health Check","description":"Check the health status of the API and its dependencies","security":[],"responses":{"200":{"description":"Health status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthResponse"},"example":{"status":"ok","environment":"development","database":"connected","supabase":"connected","timestamp":"2024-01-01T00:00:00.000Z"}}}}}}},"/api/test/data":{"get":{"tags":["System"],"summary":"Database Test","description":"Test database connectivity and retrieve sample data counts","responses":{"200":{"description":"Database test results","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Database test successful"},"requestedBy":{"type":"string","format":"uuid"},"counts":{"type":"object","properties":{"users":{"type":"integer"},"categories":{"type":"integer"},"courses":{"type":"integer"}}},"sampleUsers":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"}}}},"environment":{"type":"string"}}}}}},"500":{"description":"Database test failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/me":{"get":{"tags":["Authentication"],"summary":"Get Current User","description":"Retrieve the profile of the currently authenticated user","responses":{"200":{"description":"Current user information","content":{"application/json":{"schema":{"type":"object","properties":{"user":{"$ref":"#/components/schemas/User"},"message":{"type":"string","example":"Authentication successful"}}}}}},"401":{"description":"Authentication failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Unauthorized","message":"Authorization header is required","code":"MISSING_AUTH_HEADER","timestamp":"2024-01-01T00:00:00.000Z"}}}}}}},"/api/admin/dashboard/stats":{"get":{"tags":["Admin - Dashboard"],"summary":"Get Dashboard Statistics","description":"Get comprehensive platform statistics. Requires Clerk JWT with X-Require-Org header for organization verification. ⚡ Performance optimized with JWT caching (5min TTL).","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"},"description":"Set to 'true' to enforce organization membership check"}],"responses":{"200":{"description":"Dashboard statistics successfully retrieved","content":{"application/json":{"schema":{"type":"object","properties":{"stats":{"type":"object","properties":{"totalUsers":{"type":"number","example":1250},"totalCategories":{"type":"number","example":15},"totalCourses":{"type":"number","example":45},"activeSubscriptions":{"type":"number","example":567}}},"requestedBy":{"type":"object","properties":{"userId":{"type":"string","example":"user_xxx"},"email":{"type":"string","example":"admin@example.com"},"orgId":{"type":"string","example":"org_xxx"}}},"timestamp":{"type":"string","example":"2025-10-12T10:30:00.000Z"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/admin/dashboard/subcount":{"get":{"tags":["Admin - Dashboard"],"summary":"Get Active Subscriptions Count","description":"Get count of active subscriptions with optional filtering by payment plan. ⚡ **Cached for 30 seconds** for optimal performance. Response includes 'fromCache' field to indicate cache hit.","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"},"description":"Set to 'true' to enforce organization membership check"},{"name":"paymentPlanId","in":"query","required":false,"schema":{"type":"string"},"description":"Filter by specific payment plan ID"}],"responses":{"200":{"description":"Subscription count successfully retrieved","content":{"application/json":{"schema":{"type":"object","properties":{"count":{"type":"number","example":42},"paymentPlanId":{"type":"string","example":"all"},"fromCache":{"type":"boolean","example":true,"description":"True if result was served from cache (30s TTL)"},"requestedBy":{"type":"object","properties":{"userId":{"type":"string"},"email":{"type":"string"},"orgId":{"type":"string"}}},"timestamp":{"type":"string"}}}}}},"401":{"$ref":"#/components/responses/UnauthorizedError"},"403":{"$ref":"#/components/responses/ForbiddenError"}}}},"/api/admin/dashboard/cache-stats":{"get":{"tags":["Admin - Dashboard"],"summary":"Get Cache Statistics","description":"View cache performance metrics including total entries, active entries, and expired entries. Useful for monitoring cache efficiency.","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}}],"responses":{"200":{"description":"Cache statistics","content":{"application/json":{"schema":{"type":"object","properties":{"stats":{"type":"object","properties":{"total":{"type":"number","example":45,"description":"Total cache entries"},"active":{"type":"number","example":40,"description":"Non-expired entries"},"expired":{"type":"number","example":5,"description":"Expired entries (cleaned periodically)"}}},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}}},"/api/admin/dashboard/clear-cache":{"post":{"tags":["Admin - Dashboard"],"summary":"Clear Cache Entries","description":"Clear all cache entries or entries matching a specific pattern. Use this after data updates to ensure fresh data.","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"pattern":{"type":"string","example":"subcount","description":"Optional pattern to match cache keys (e.g., 'subcount', 'jwt')"}}},"examples":{"clearAll":{"summary":"Clear all cache","value":{}},"clearPattern":{"summary":"Clear specific pattern","value":{"pattern":"subcount"}}}}}},"responses":{"200":{"description":"Cache cleared successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Cache cleared for pattern: subcount"},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}}},"/api/admin/users":{"get":{"tags":["Admin - Users"],"summary":"Get All Users (Paginated)","description":"Retrieve all users with pagination support. Requires organization membership verification.","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"limit","in":"query","schema":{"type":"integer","default":50,"maximum":100},"description":"Number of users to return"},{"name":"offset","in":"query","schema":{"type":"integer","default":0},"description":"Pagination offset"}],"responses":{"200":{"description":"Users list retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"users":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"clerkId":{"type":"string"},"email":{"type":"string"},"name":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"isAdmin":{"type":"boolean"},"createdAt":{"type":"string"},"updatedAt":{"type":"string"}}}},"pagination":{"type":"object","properties":{"limit":{"type":"integer"},"offset":{"type":"integer"},"total":{"type":"integer"}}},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}},"post":{"tags":["Admin - Users"],"summary":"Create New User","description":"Create a new user in the system","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["clerkId","email"],"properties":{"clerkId":{"type":"string"},"email":{"type":"string","format":"email"},"name":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"}}}}}},"responses":{"201":{"description":"User created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"user":{"type":"object"},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}}},"/api/admin/users/{id}":{"get":{"tags":["Admin - Users"],"summary":"Get User by ID","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"},"description":"User ID"}],"responses":{"200":{"description":"User details"},"404":{"description":"User not found"}}},"patch":{"tags":["Admin - Users"],"summary":"Update User","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string"},"email":{"type":"string"},"isAdmin":{"type":"boolean"}}}}}},"responses":{"200":{"description":"User updated successfully"},"404":{"description":"User not found"}}},"delete":{"tags":["Admin - Users"],"summary":"Delete User","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"User deleted successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string"},"deletedUser":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"}}}}}}}},"404":{"description":"User not found"}}}},"/api/admin/forms":{"get":{"tags":["Admin - Forms"],"summary":"Get All Forms","description":"Retrieve all forms with their configurations","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}}],"responses":{"200":{"description":"Forms list retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"forms":{"type":"array","items":{"type":"object"}},"count":{"type":"integer"},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}},"post":{"tags":["Admin - Forms"],"summary":"Create New Form","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["title"],"properties":{"title":{"type":"string"},"description":{"type":"string"},"fields":{"type":"array"}}}}}},"responses":{"201":{"description":"Form created successfully"}}}},"/api/admin/forms/{id}":{"get":{"tags":["Admin - Forms"],"summary":"Get Form by ID","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Form details"},"404":{"description":"Form not found"}}},"patch":{"tags":["Admin - Forms"],"summary":"Update Form","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"title":{"type":"string"},"description":{"type":"string"},"fields":{"type":"array"}}}}}},"responses":{"200":{"description":"Form updated successfully"},"404":{"description":"Form not found"}}},"delete":{"tags":["Admin - Forms"],"summary":"Delete Form","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Form deleted successfully"},"404":{"description":"Form not found"}}}},"/api/admin/forms/{id}/submissions":{"get":{"tags":["Admin - Forms"],"summary":"Get Form Submissions","description":"Get all submissions for a specific form with pagination","security":[{"BearerAuth":[]}],"parameters":[{"name":"X-Require-Org","in":"header","required":true,"schema":{"type":"string","example":"true"}},{"name":"id","in":"path","required":true,"schema":{"type":"string"},"description":"Form ID"},{"name":"limit","in":"query","schema":{"type":"integer","default":50}},{"name":"offset","in":"query","schema":{"type":"integer","default":0}}],"responses":{"200":{"description":"Form submissions retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"submissions":{"type":"array"},"formId":{"type":"string"},"pagination":{"type":"object"},"requestedBy":{"type":"object"},"timestamp":{"type":"string"}}}}}}}}},"/api/users":{"get":{"tags":["Users"],"summary":"Get Users","description":"Retrieve a paginated list of users using enterprise-grade controllers and services architecture","parameters":[{"name":"page","in":"query","description":"Page number (starts from 1)","schema":{"type":"integer","minimum":1,"default":1}},{"name":"limit","in":"query","description":"Number of users per page (maximum 100 for performance)","schema":{"type":"integer","minimum":1,"maximum":100,"default":10}}],"responses":{"200":{"description":"Paginated list of users","content":{"application/json":{"schema":{"type":"object","properties":{"users":{"type":"array","items":{"$ref":"#/components/schemas/User"}},"pagination":{"type":"object","properties":{"page":{"type":"integer"},"limit":{"type":"integer"},"total":{"type":"integer"},"totalPages":{"type":"integer"},"hasNextPage":{"type":"boolean"},"hasPreviousPage":{"type":"boolean"}}}}}}}},"400":{"description":"Validation error for pagination parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Database error while fetching users","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/api/users/{id}":{"get":{"tags":["Users"],"summary":"Get User by ID","description":"Retrieve a specific user by their unique identifier using enterprise service layer","parameters":[{"name":"id","in":"path","required":true,"description":"Unique user identifier (UUID format)","schema":{"type":"string","format":"uuid"}}],"responses":{"200":{"description":"User details","content":{"application/json":{"schema":{"type":"object","properties":{"user":{"$ref":"#/components/schemas/User"}}},"example":{"user":{"id":"123e4567-e89b-12d3-a456-426614174000","email":"john@example.com","name":"John Doe","firstName":"John","lastName":"Doe","isVerified":true,"createdAt":"2024-01-01T00:00:00.000Z"}}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Validation failed"},"message":{"type":"string","example":"User ID is required and must be a non-empty string"},"code":{"type":"string","example":"VALIDATION_ERROR"}}}}}},"404":{"description":"User not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"User with ID '123' not found"},"code":{"type":"string","example":"NOT_FOUND"}}}}}},"500":{"description":"Database error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Failed to fetch user"},"code":{"type":"string","example":"DATABASE_ERROR"}}}}}}}}},"/api/users/me/profile":{"get":{"tags":["Users"],"summary":"Get Current User Profile","description":"Retrieve the profile of the currently authenticated user using Clerk ID lookup","responses":{"200":{"description":"Current user profile","content":{"application/json":{"schema":{"type":"object","properties":{"user":{"$ref":"#/components/schemas/User"}}},"example":{"user":{"id":"123e4567-e89b-12d3-a456-426614174000","email":"current@example.com","name":"Current User","firstName":"Current","lastName":"User","isVerified":true,"createdAt":"2024-01-01T00:00:00.000Z"}}}}},"404":{"description":"User profile not found","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"User profile not found"},"code":{"type":"string","example":"NOT_FOUND"}}}}}},"500":{"description":"Database error","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","example":"Failed to fetch user profile"},"code":{"type":"string","example":"DATABASE_ERROR"}}}}}}}}},"/video/qualities":{"get":{"tags":["Video Processing"],"summary":"Get Video Quality Options","description":"Retrieve available video quality options with their specifications and cost implications","security":[],"responses":{"200":{"description":"Available video quality options","content":{"application/json":{"schema":{"type":"object","properties":{"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQualityOption"}},"total":{"type":"integer","example":5}}},"example":{"qualities":[{"id":"540p","name":"540P","width":960,"height":540,"bitrate":3500000,"preset":"System-Avc_16x9_540p_29_97fps_3500kbps","recommended":false},{"id":"720p","name":"720P","width":1280,"height":720,"bitrate":5000000,"preset":"System-Avc_16x9_720p_29_97fps_5000kbps","recommended":true}],"total":5}}}}}}},"/video/cost-estimate":{"post":{"tags":["Video Processing"],"summary":"Get Processing Cost Estimate","description":"Calculate estimated processing cost and time for selected video qualities","security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["qualities"],"properties":{"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"},"minItems":1,"example":["720p","1080p"]}}}}}},"responses":{"200":{"description":"Cost estimate and validation results","content":{"application/json":{"schema":{"type":"object","properties":{"validation":{"$ref":"#/components/schemas/QualityValidation"},"estimate":{"$ref":"#/components/schemas/CostEstimate"},"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"}}}}}}},"400":{"description":"Invalid quality selection","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/video/upload-url":{"post":{"tags":["Video Processing"],"summary":"Generate Upload URL","description":"Generate a presigned S3 URL for direct video upload with proper organization by entity type","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UploadUrlRequest"},"example":{"fileName":"lesson-intro.mp4","contentType":"video/mp4","entityType":"lesson","entityId":"123e4567-e89b-12d3-a456-426614174000","metadata":{"description":"Introduction video for lesson","duration":"300"}}}}},"responses":{"200":{"description":"Presigned upload URL generated successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UploadUrlResponse"},"example":{"success":true,"uploadUrl":"https://tcm-courses-input.s3.amazonaws.com/lessons/123e4567-e89b-12d3-a456-426614174000/lesson-intro-1642681234567.mp4?X-Amz-Algorithm=...","fileKey":"lessons/123e4567-e89b-12d3-a456-426614174000/lesson-intro-1642681234567.mp4","fileUrl":"https://dufe1umrgsnhb.cloudfront.net/lessons/123e4567-e89b-12d3-a456-426614174000/lesson-intro-1642681234567.mp4","expiresIn":3600}}}},"400":{"description":"Validation error in request parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Failed to generate upload URL","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/video/process":{"post":{"tags":["Video Processing"],"summary":"Trigger Video Processing","description":"Start automated video processing workflow with MediaConvert and Inngest for uploaded videos","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProcessVideoRequest"},"example":{"entityType":"lesson","entityId":"123e4567-e89b-12d3-a456-426614174000","sourceFileKey":"lessons/123e4567-e89b-12d3-a456-426614174000/lesson-intro-1642681234567.mp4","sourceFileUrl":"https://dufe1umrgsnhb.cloudfront.net/lessons/123e4567-e89b-12d3-a456-426614174000/lesson-intro-1642681234567.mp4","qualities":["720p","1080p"],"metadata":{"description":"Lesson introduction video","expectedDuration":"300"}}}}},"responses":{"200":{"description":"Video processing started successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProcessVideoResponse"},"example":{"success":true,"message":"Video processing started","entityType":"lesson","entityId":"123e4567-e89b-12d3-a456-426614174000","qualities":["720p","1080p"],"estimate":{"estimatedMinutes":27,"estimatedCost":0.45,"breakdown":{"720p":{"minutes":12,"cost":0.15},"1080p":{"minutes":15,"cost":0.3}}},"warnings":[]}}}},"400":{"description":"Invalid request or quality selection","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Failed to start video processing","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/video/upload-and-process":{"post":{"tags":["Video Processing"],"summary":"Upload and Process Combined","description":"Combined endpoint that generates upload URL and prepares processing configuration in one request","requestBody":{"required":true,"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/UploadUrlRequest"},{"type":"object","required":["qualities"],"properties":{"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"},"minItems":1}}}]},"example":{"fileName":"course-demo.mp4","contentType":"video/mp4","entityType":"course","entityId":"456e7890-e89b-12d3-a456-426614174000","qualities":["720p","1080p"],"metadata":{"description":"Course demonstration video"}}}}},"responses":{"200":{"description":"Upload URL generated with processing configuration","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/UploadUrlResponse"},{"type":"object","properties":{"processing":{"type":"object","properties":{"qualities":{"type":"array","items":{"$ref":"#/components/schemas/VideoQuality"}},"estimate":{"$ref":"#/components/schemas/CostEstimate"},"warnings":{"type":"array","items":{"type":"string"}}}},"instructions":{"type":"object","properties":{"step1":{"type":"string"},"step2":{"type":"string"},"step3":{"type":"string"}}}}}]}}}},"400":{"description":"Validation error or invalid quality selection","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Failed to setup upload and processing","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/webhook/acuity":{"post":{"tags":["Webhooks"],"summary":"Acuity Scheduling Webhook","description":"Receives webhook notifications from Acuity Scheduling when appointments are created, updated, or cancelled. Automatically processes appointment data and stores it in the database with proper field mapping.","security":[],"requestBody":{"required":true,"content":{"application/x-www-form-urlencoded":{"schema":{"type":"object","properties":{"action":{"type":"string","enum":["changed","created","cancelled"],"description":"Type of action that triggered the webhook","example":"changed"},"id":{"type":"string","description":"Acuity appointment ID","example":"1482410705"},"calendarID":{"type":"string","description":"Acuity calendar ID","example":"11728056"},"appointmentTypeID":{"type":"string","description":"Acuity appointment type ID","example":"10604085"}},"required":["action","id"]},"example":"action=changed&id=1482410705&calendarID=11728056&appointmentTypeID=10604085"}}},"responses":{"200":{"description":"Webhook processed successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AcuityWebhookSuccessResponse"},"example":{"message":"Successfully processed appointment 1482410705","appointmentId":1482410705}}}},"400":{"description":"Webhook processing failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AcuityWebhookErrorResponse"},"example":{"error":"No appointment ID found in webhook body","code":"MISSING_APPOINTMENT_ID"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/webhook/stripe":{"post":{"tags":["Webhooks"],"summary":"Stripe Payment Webhook","description":"Receives webhook notifications from Stripe for payment events. Verifies webhook signatures and processes payment intents (created, succeeded, failed). Ensures secure handling of payment data.","security":[],"parameters":[{"name":"stripe-signature","in":"header","required":true,"description":"Stripe webhook signature for request verification","schema":{"type":"string"},"example":"t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StripeWebhookEvent"},"example":{"id":"evt_1234567890","object":"event","created":1326853478,"data":{"object":{"id":"pi_1234567890","object":"payment_intent","amount":2000,"currency":"usd","status":"succeeded"}},"livemode":false,"pending_webhooks":1,"request":{"id":"req_1234567890","idempotency_key":null},"type":"payment_intent.succeeded"}}}},"responses":{"200":{"description":"Webhook processed successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StripeWebhookSuccessResponse"},"example":{"message":"Webhook processed successfully"}}}},"400":{"description":"Webhook verification failed or invalid request","content":{"application/json":{"schema":{"$ref":"#/components/schemas/StripeWebhookErrorResponse"},"example":{"error":"Webhook signature verification failed","code":"WEBHOOK_VERIFICATION_FAILED"}}}},"500":{"description":"Internal server error during processing","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/automations/lesson-upgrade-cta-clicked":{"post":{"tags":["Automations"],"summary":"Queue lesson upgrade CTA retarget workflow","description":"Queues an Inngest workflow when a user clicks a lesson upgrade CTA. The workflow waits before checking appointment state and triggers retargeting only when no upcoming active appointment exists.","security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["event","userId","email","courseId","lessonId","lessonNumber","clickedAt","source"],"properties":{"event":{"type":"string","enum":["lesson_upgrade_cta_clicked"],"example":"lesson_upgrade_cta_clicked"},"userId":{"type":"string","example":"a7922d1d-4321-4a0e-9e7e-6c58981df001"},"email":{"type":"string","format":"email","example":"student@example.com"},"courseId":{"type":"string","example":"university-course-1"},"lessonId":{"type":"string","example":"lesson-12"},"lessonNumber":{"type":"integer","minimum":1,"example":12},"clickedAt":{"type":"string","format":"date-time","example":"2026-04-23T10:30:00.000Z"},"source":{"type":"string","example":"lesson_navigation_upgrade_cta"}}}}}},"responses":{"200":{"description":"Workflow accepted","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"accepted":{"type":"boolean","example":true},"workflowId":{"type":"string","example":"lesson-upgrade-cta:a7922d1d-4321-4a0e-9e7e-6c58981df001:university-course-1:lesson-12:1975886"}}}}}},"400":{"description":"Invalid JSON or validation payload error","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"accepted":{"type":"boolean","example":false},"error":{"type":"string","example":"Invalid payload"}}}}}},"500":{"description":"Failed to queue workflow","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":false},"accepted":{"type":"boolean","example":false},"error":{"type":"string","example":"Failed to queue lesson upgrade CTA workflow"}}}}}}}}},"/automations/inngest":{"get":{"tags":["Automations"],"summary":"Inngest Event Handler","description":"\n**Inngest Event Processing Endpoint**\n\nThis endpoint serves as the main handler for all Inngest automation events and workflows.\n\n### What is Inngest?\nInngest is our automation platform that handles:\n- **Scheduled Cron Jobs**: Daily, hourly, weekly, and monthly tasks\n- **Event-Driven Workflows**: User actions triggering background processes  \n- **Reliable Execution**: Automatic retries, error handling, and observability\n- **Background Processing**: Long-running tasks without blocking API responses\n\n### Active Cron Jobs & Schedules:\n\n#### 🕘 **Hourly Jobs (Every hour at minute 0)**\n- **`meta-ads-sync`** - Meta campaign, ad set and ad spend (4 ad accounts), one account at a time\n  - **Schedule**: `\"5 * * * *\"` (hourly: yesterday + today). The 02:05 UTC run is the daily one: last 7 days + breakdowns + ads list, and re-pulls any day since 2026-04-01 that never synced properly (`meta_sync_days`)\n  - **Reliability**: honours Meta usage headers, waits out rate limits, OneBot alerts in OneChat (`ONECHAT_ALERTS_CHANNEL_ID`) when an account keeps failing and when it recovers (`meta_sync_health`)\n  - **On request**: event `meta/sync.requested` with `{ mode: \"backfill\", from, to, accountIds?, parts? }` or `{ mode: \"heal\", from?, to? }`\n  - **After saving**: refreshes the OneAnalytics mega table cache (`mega_facts_refresh`)\n- **`ads-migrate`** - Apple Search Ads (Google Ads arrives via its script webhook)\n  - **Schedule**: `\"0 * * * *\"` (every hour)\n  - **Storage**: Supabase `campaigns` and `campaign_metrics` tables\n\n#### 🌅 **Daily Jobs**\n- **`dailyProgressReport`** - User progress and engagement summary\n  - **Schedule**: `\"0 9 * * *\"` (9:00 AM daily)\n  - **Function**: Analyze user activity, course progress, completion rates\n  \n- **`dailyDatabaseCleanup`** - Maintenance and optimization\n  - **Schedule**: `\"0 2 * * *\"` (2:00 AM daily)  \n  - **Function**: Clean expired sessions, optimize tables, remove temp files\n\n#### 📅 **Weekly Jobs**\n- **`weeklyEngagementReport`** - Platform analytics and insights\n  - **Schedule**: `\"0 8 * * 1\"` (Monday 8:00 AM)\n  - **Function**: Weekly user engagement, content performance, growth metrics\n\n#### 📊 **Monthly Jobs**  \n- **`monthlySubscriptionSync`** - Subscription and billing sync\n  - **Schedule**: `\"0 3 1 * *\"` (1st of month, 3:00 AM)\n  - **Function**: Sync Stripe subscriptions, update user membership levels\n\n#### ⚡ **Health Monitoring**\n- **`hourlyHealthCheck`** - System health monitoring\n  - **Schedule**: `\"0 * * * *\"` (every hour)\n  - **Function**: Check database, APIs, external services\n\n### 🔧 **Development & Deployment**\n\n#### **Local Development**\n```bash\n# Start Inngest dev server (with Bun)\nbunx inngest-cli@latest dev\n\n# Alternative with pnpm  \npnpm dlx inngest-cli@latest dev\n\n# Alternative with npm\nnpx inngest-cli@latest dev\n```\n\n#### **Deploy Changes**\n1. **Code Changes**: Make changes to functions in `src/automations/functions/`\n2. **Test Locally**: Use Inngest dev server to test functions\n3. **Deploy**: Push to main branch - Inngest auto-syncs from this endpoint\n4. **Monitor**: Check Inngest dashboard for execution logs\n\n#### **Inngest Dashboard**\n- **Production**: https://app.inngest.com/env/production\n- **Development**: https://app.inngest.com/env/development\n- **Function Logs**: Real-time execution logs and error tracking\n- **Metrics**: Success rates, execution times, retry counts\n\n### 📁 **File Structure**\n```\nsrc/automations/\n├── index.ts              # Export all functions to Inngest\n├── inngest.ts            # Inngest client configuration  \n├── functions/\n│   ├── scheduled-tasks.ts     # Weekly/monthly/health cron jobs\n│   ├── ads-migrate.ts         # Apple ads job + shared Supabase storage helpers\n│   ├── meta-ads-sync.ts       # Meta ads hourly/daily/backfill sync + alerts\n│   ├── meta-ads.ts           # Meta Ads API integration\n│   ├── google-ads.ts         # Google Ads API integration\n│   └── daily-reports.ts      # Daily progress reports\n└── utils/\n    ├── currency-helper.ts     # GBP to USD conversion\n    └── google-auth-helper.ts  # Auto-refresh Google tokens\n```\n\n### 🚨 **Error Handling & Monitoring**\n- **Auto-Retries**: Failed functions retry up to 3 times with exponential backoff\n- **Error Logs**: All errors logged to Inngest dashboard with full stack traces  \n- **Platform Independence**: Meta/Google failures don't affect each other\n- **Token Refresh**: Google Ads tokens auto-refresh on auth failures\n- **Graceful Degradation**: Individual automation failures don't break the system\n\n### 📊 **Data Flow Example (Ads Migration)**\n```\n⏰ Hourly Trigger (XX:00)\n↓\n🔄 Refresh Google Ads tokens\n↓  \n📊 Fetch Meta Ads data (3 accounts)\n↓\n📊 Fetch Google Ads data (1 account)  \n↓\n🔄 Process & flatten data\n↓\n💾 Store in Supabase (campaigns + metrics)\n↓\n📝 Log success/failure metrics\n```\n      ","security":[],"responses":{"200":{"description":"Inngest event processed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"message":{"type":"string","example":"Inngest event processed"},"timestamp":{"type":"string","format":"date-time"},"environment":{"type":"string","example":"development"}}}}}},"400":{"description":"Invalid Inngest event data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Automation execution failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}},"post":{"tags":["Automations"],"summary":"Inngest Event Handler (POST)","description":"Handle incoming Inngest events and workflow executions","security":[],"requestBody":{"description":"Inngest event payload","required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"event":{"type":"object","description":"Inngest event data"},"step":{"type":"object","description":"Inngest step context"}}}}}},"responses":{"200":{"description":"Event processed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean"},"functionId":{"type":"string"},"executionTime":{"type":"number"},"result":{"type":"object"}}}}}}}},"put":{"tags":["Automations"],"summary":"Inngest Sync & Registration","description":"\n**Inngest Function Registration & Sync**\n\nThis endpoint handles Inngest's automatic function registration and synchronization.\n\n### What happens here:\n- **Function Discovery**: Inngest scans our exported functions\n- **Schedule Registration**: Cron jobs are registered with their schedules\n- **Function Updates**: Changes to function code are auto-detected\n- **Health Checks**: Inngest verifies function availability\n\n### Note:\nYou'll see frequent PUT requests to this endpoint (~every 5 seconds) in your logs. \nThis is **normal behavior** - it's Inngest's sync mechanism, not our cron jobs running.\n      ","security":[],"responses":{"200":{"description":"Functions registered successfully","content":{"application/json":{"schema":{"type":"object","properties":{"registered":{"type":"array","items":{"type":"string"}},"schedules":{"type":"array","items":{"type":"string"}},"timestamp":{"type":"string","format":"date-time"}}}}}}}}},"/ffmpeg/health":{"get":{"tags":["FFmpeg Video Processing"],"summary":"FFmpeg Service Health Check","description":"Check the health status of the FFmpeg video processing service, including supported qualities and active connections","security":[],"responses":{"200":{"description":"Service health status and configuration","content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","example":"ok"},"service":{"type":"string","example":"ffmpeg-video-processing"},"supportedQualities":{"type":"array","items":{"type":"string"},"example":["720p","1080p"]},"defaultQualities":{"type":"array","items":{"type":"string"},"example":["1080p","720p"]},"outputFormat":{"type":"string","example":"HLS (m3u8)"},"timestamp":{"type":"string","format":"date-time"},"qualityConfigs":{"$ref":"#/components/schemas/QualityConfigs"},"activeConnections":{"type":"integer","example":3},"endpoints":{"type":"object","properties":{"upload":{"type":"string","example":"POST /ffmpeg/upload (multipart/form-data)"},"convertUrl":{"type":"string","example":"POST /ffmpeg/convert-to-hls (JSON)"},"progress":{"type":"string","example":"GET /ffmpeg/progress/:sessionId (SSE)"},"health":{"type":"string","example":"GET /ffmpeg/health"},"cleanup":{"type":"string","example":"POST /ffmpeg/cleanup"}}}}}}}}}}},"/ffmpeg/upload":{"post":{"tags":["FFmpeg Video Processing"],"summary":"Direct Video Upload & Processing","description":"Upload a video file directly and process it to HLS format with multiple quality variants. Supports real-time progress tracking via Server-Sent Events (SSE).","security":[],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","required":["video","sessionId"],"properties":{"video":{"type":"string","format":"binary","description":"Video file to process (supports most video formats)"},"sessionId":{"type":"string","description":"Unique session ID for progress tracking via SSE","example":"session_1640995200000_abc123def"},"outputFileName":{"type":"string","description":"Custom output filename (optional)","example":"my-video"},"qualities":{"type":"string","description":"Comma-separated list of qualities to generate","example":"1080p,720p"}}}}}},"responses":{"200":{"description":"Video processing completed successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FFmpegProcessingResult"},"example":{"success":true,"message":"Video successfully processed to HLS format in 3 qualities","outputs":[{"quality":"1080p","hlsUrl":"https://your-supabase-url.supabase.co/storage/v1/object/public/hls/my-video-1080p.m3u8","segmentCount":15},{"quality":"720p","hlsUrl":"https://your-supabase-url.supabase.co/storage/v1/object/public/hls/my-video-720p.m3u8","segmentCount":15},{"quality":"720p","hlsUrl":"https://your-supabase-url.supabase.co/storage/v1/object/public/hls/my-video-540p.m3u8","segmentCount":15}],"totalQualities":3,"sessionId":"session_1640995200000_abc123def"}}}},"400":{"description":"Bad request - missing video file or session ID","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"No video file provided"}}}},"500":{"description":"Video processing failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"},"example":{"error":"Video processing failed","message":"FFmpeg process failed with code 1"}}}}}}},"/ffmpeg/convert-to-hls":{"post":{"tags":["FFmpeg Video Processing"],"summary":"Convert Video URL to HLS","description":"Download a video from a URL and convert it to HLS format with multiple quality variants. Supports real-time progress tracking via Server-Sent Events (SSE).","security":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FFmpegUrlProcessingRequest"},"example":{"videoUrl":"https://example.com/video.mp4","sessionId":"session_1640995200000_abc123def","outputFileName":"my-video","qualities":["1080p","720p"]}}}},"responses":{"200":{"description":"Video processing completed successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FFmpegProcessingResult"}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"},"example":{"error":"Validation failed","details":[{"code":"invalid_string","message":"Invalid video URL","path":["videoUrl"]}]}}}},"500":{"description":"Video processing failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}},"get":{"tags":["FFmpeg Video Processing"],"summary":"Convert Video URL to HLS (GET)","description":"Alternative GET endpoint for converting video URLs to HLS format. Useful for testing and simple integrations.","security":[],"parameters":[{"name":"videoUrl","in":"query","required":true,"schema":{"type":"string","format":"uri"},"description":"URL of the video to process","example":"https://example.com/video.mp4"},{"name":"sessionId","in":"query","required":false,"schema":{"type":"string"},"description":"Session ID for progress tracking","example":"session_1640995200000_abc123def"},{"name":"outputFileName","in":"query","required":false,"schema":{"type":"string"},"description":"Custom output filename","example":"my-video"},{"name":"qualities","in":"query","required":false,"schema":{"type":"string"},"description":"Comma-separated list of qualities","example":"1080p,720p,540p"}],"responses":{"200":{"description":"Video processing completed successfully","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FFmpegProcessingResult"}}}},"400":{"description":"Validation error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidationError"}}}},"500":{"description":"Video processing failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}},"/ffmpeg/progress/{sessionId}":{"get":{"tags":["FFmpeg Video Processing"],"summary":"Real-time Progress Stream (SSE)","description":"Server-Sent Events (SSE) endpoint providing real-time progress updates during video processing. Connect to this endpoint before starting processing to receive live updates.","security":[],"parameters":[{"name":"sessionId","in":"path","required":true,"schema":{"type":"string"},"description":"Unique session ID for tracking progress","example":"session_1640995200000_abc123def"}],"responses":{"200":{"description":"Server-Sent Events stream with progress updates","content":{"text/event-stream":{"schema":{"type":"string","description":"Server-Sent Events stream with JSON-encoded progress updates"},"examples":{"connected":{"summary":"Connection established","value":"event: connected\ndata: {\"stage\":\"connected\",\"progress\":0,\"message\":\"Connected to progress stream\"}\n\n"},"downloading":{"summary":"File download progress","value":"event: progress\ndata: {\"stage\":\"downloading\",\"progress\":30,\"message\":\"Video downloaded successfully\",\"totalQualities\":3,\"details\":{\"size\":52428800}}\n\n"},"processing":{"summary":"Video processing progress","value":"event: progress\ndata: {\"stage\":\"processing\",\"progress\":65,\"message\":\"Processing 720p: 45%\",\"quality\":\"720p\",\"currentQuality\":2,\"totalQualities\":3}\n\n"},"completed":{"summary":"Processing completed","value":"event: progress\ndata: {\"stage\":\"completed\",\"progress\":100,\"message\":\"Successfully processed 3 quality variants\",\"totalQualities\":3,\"details\":{\"outputs\":[...]}}\n\n"}}}}}}}},"/ffmpeg/cleanup":{"post":{"tags":["FFmpeg Video Processing"],"summary":"Cleanup Temporary Files","description":"Remove temporary files older than specified hours (default: 24 hours)","security":[],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"olderThanHours":{"type":"integer","minimum":1,"default":24,"description":"Remove files older than this many hours","example":24}}}}}},"responses":{"200":{"description":"Cleanup completed successfully","content":{"application/json":{"schema":{"type":"object","properties":{"success":{"type":"boolean","example":true},"message":{"type":"string","example":"Temporary files cleaned up successfully"}}}}}},"500":{"description":"Cleanup failed","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"tags":[{"name":"System","description":"System health and information endpoints"},{"name":"Authentication","description":"User authentication and authorization"},{"name":"Users","description":"User management and profiles"},{"name":"Courses","description":"Learning content and course management"},{"name":"Social","description":"Social platform features - posts, comments, likes"},{"name":"Video Processing","description":"Automated video processing, transcoding, and delivery system"},{"name":"FFmpeg Video Processing","description":"Direct video upload and processing to HLS format with real-time progress tracking via Server-Sent Events"},{"name":"Admin - Dashboard","description":"Admin dashboard endpoints for statistics and analytics. Requires Clerk JWT + X-Require-Org header. Includes performance caching (5min JWT cache, 30s query cache)."},{"name":"Admin - Users","description":"Admin user management endpoints (CRUD operations). Requires organization membership verification."},{"name":"Admin - Forms","description":"Admin form management endpoints including form submissions. Requires organization membership verification."},{"name":"Webhooks","description":"External webhook integrations for Acuity Scheduling and Stripe payments"},{"name":"Automations","description":"Inngest-powered cron jobs, scheduled tasks, and background workflows for ads data collection, reporting, and system maintenance"}]}