/** * Enhanced Proxy Controller with Unified Conversation Management * * Integrates the UnifiedConversationService with the existing proxy server * to provide comprehensive conversation handling and analytics. */ import { type UnifiedConversationService, type UnifiedConversationConfig, type ConversationResponse } from '@buzztrail/shared/services'; import type { Conversation as _Conversation, ConversationAnalytics as _ConversationAnalytics, WebhookEvent as _WebhookEvent } from '@buzztrail/shared-database'; export interface AuthenticatedRequest { customerId: string; userId?: string; role?: string; headers: Record; body?: any; query?: Record; params?: Record; } export interface ConversationCreationRequest { persona_id: string; replica_id?: string; conversation_name?: string; callback_url?: string; room_config?: { participant_left_timeout?: number; enable_closed_captions?: boolean; enable_chat?: boolean; enable_screenshare?: boolean; max_participants?: number; room_privacy?: 'public' | 'private'; }; } export interface ConversationValidationResult { valid: boolean; message?: string; errors?: string[]; } /** * Enhanced Proxy Controller * * Handles conversation management endpoints with unified service integration */ export class EnhancedProxyController { private conversationService: UnifiedConversationService; constructor(conversationService: UnifiedConversationService) { this.conversationService = conversationService; } /** * Create conversation with unified service */ async createConversation(req: AuthenticatedRequest): Promise { try { const config: UnifiedConversationConfig = { ...req.body as ConversationCreationRequest, customer_id: req.customerId, environment: process.env.NODE_ENV as 'development' | 'staging' | 'production' || 'development' }; // Validate configuration const validation = await this.validateConversationConfig(config); if (!validation.valid) { return new Response(JSON.stringify({ error: 'invalid_configuration', message: validation.message, details: validation.errors }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } // Create conversation with unified service const conversation = await this.conversationService.createConversation(config); // Log conversation creation for analytics await this.logConversationCreation(req.customerId, conversation, req.headers); return new Response(JSON.stringify({ conversation_id: conversation.conversation_id, conversation_name: conversation.conversation_name, status: conversation.status, conversation_url: conversation.conversation_url, daily_room_url: conversation.daily_room_url, created_at: conversation.created_at, room_config: conversation.room_config }), { status: 201, headers: { 'Content-Type': 'application/json' } }); } catch (error) { console.error('Conversation creation failed:', error); return new Response(JSON.stringify({ error: 'conversation_creation_failed', message: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } /** * Get conversation details with optional analytics */ async getConversation(req: AuthenticatedRequest): Promise { try { const conversationId = req.params?.id; if (!conversationId) { return new Response(JSON.stringify({ error: 'missing_conversation_id', message: 'Conversation ID is required' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const verbose = req.query?.verbose === 'true'; const conversation = await this.conversationService.getConversationWithAnalytics( req.customerId, conversationId, verbose ); if (!conversation) { return new Response(JSON.stringify({ error: 'conversation_not_found', message: 'Conversation not found or access denied' }), { status: 404, headers: { 'Content-Type': 'application/json' } }); } return new Response(JSON.stringify(conversation), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (error) { console.error('Failed to get conversation:', error); return new Response(JSON.stringify({ error: 'conversation_retrieval_failed', message: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } /** * List conversations for customer */ async listConversations(req: AuthenticatedRequest): Promise { try { // Extract query parameters const filters = { status: req.query?.status as string, environment: req.query?.environment as string, start_date: req.query?.start_date as string, end_date: req.query?.end_date as string, page: parseInt(req.query?.page as string) || 1, limit: parseInt(req.query?.limit as string) || 50 }; // This would typically call a database service // For now, return a placeholder response const conversations = await this.getCustomerConversations(req.customerId, filters); return new Response(JSON.stringify({ conversations, pagination: { page: filters.page, limit: filters.limit, total: conversations.length } }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (error) { console.error('Failed to list conversations:', error); return new Response(JSON.stringify({ error: 'conversation_list_failed', message: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } /** * Update conversation (end, status change, etc.) */ async updateConversation(req: AuthenticatedRequest): Promise { try { const conversationId = req.params?.id; if (!conversationId) { return new Response(JSON.stringify({ error: 'missing_conversation_id', message: 'Conversation ID is required' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const _updates = req.body; // Validate that customer owns this conversation const conversation = await this.conversationService.getConversationWithAnalytics( req.customerId, conversationId, false ); if (!conversation) { return new Response(JSON.stringify({ error: 'conversation_not_found', message: 'Conversation not found or access denied' }), { status: 404, headers: { 'Content-Type': 'application/json' } }); } // Apply updates (this would call database service) // await this.conversationService.updateConversation(conversationId, updates); return new Response(JSON.stringify({ message: 'Conversation updated successfully', conversation_id: conversationId }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } catch (error) { console.error('Failed to update conversation:', error); return new Response(JSON.stringify({ error: 'conversation_update_failed', message: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } /** * Validate conversation configuration */ private async validateConversationConfig(config: UnifiedConversationConfig): Promise { return await this.conversationService.validateConversationConfig(config); } /** * Log conversation creation for analytics */ private async logConversationCreation( customerId: string, conversation: ConversationResponse, headers: Record ): Promise { try { const logData = { customer_id: customerId, conversation_id: conversation.conversation_id, persona_id: conversation.conversation_url, // Extract from URL if needed created_at: conversation.created_at, user_agent: headers['user-agent'] || 'unknown', source_ip: headers['x-forwarded-for'] || headers['x-real-ip'] || 'unknown' }; // Log to analytics service console.log('Conversation created:', logData); // This would typically send to an analytics service // await this.analyticsService.trackConversationCreation(logData); } catch (error) { console.warn('Failed to log conversation creation:', error); } } /** * Get customer conversations with filtering */ private async getCustomerConversations(_customerId: string, _filters: any): Promise { // Placeholder implementation // This would typically query the database return [ { id: 'conv_123', conversation_name: 'Sample Conversation', persona_id: 'persona_123', status: 'created', created_at: new Date().toISOString(), duration_seconds: 0 } ]; } /** * Middleware to authenticate customer requests */ async authenticateCustomer(req: Request): Promise { try { // Extract customer ID from headers or JWT token const customerId = req.headers.get('x-customer-id'); const authHeader = req.headers.get('authorization'); if (!customerId && !authHeader) { return null; } // Basic authentication for now // In production, this would validate JWT tokens const authenticatedReq: AuthenticatedRequest = { customerId: customerId || 'unknown', headers: Object.fromEntries(req.headers.entries()), body: req.method !== 'GET' ? await req.json().catch(() => ({})) : undefined, query: Object.fromEntries(new URL(req.url).searchParams.entries()), params: this.extractPathParams(req.url) }; return authenticatedReq; } catch (error) { console.error('Authentication failed:', error); return null; } } /** * Extract path parameters from URL */ private extractPathParams(url: string): Record { const pathname = new URL(url).pathname; const params: Record = {}; // Extract conversation ID from path like /api/conversations/{id} const conversationMatch = pathname.match(/\/conversations\/([^/]+)/); if (conversationMatch) { params.id = conversationMatch[1]; } return params; } /** * Setup routes for Express app integration */ setupRoutes(app: any): void { // Enhanced conversation creation endpoint app.post('/api/conversations/create', async (req: any, res: any) => { const authReq = await this.authenticateCustomer(req); if (!authReq) { return res.status(401).json({ error: 'authentication_required', message: 'Valid authentication is required' }); } const response = await this.createConversation(authReq); const responseData = await response.json(); res.status(response.status).json(responseData); }); // Enhanced conversation retrieval endpoint app.get('/api/conversations/:id', async (req: any, res: any) => { const authReq = await this.authenticateCustomer(req); if (!authReq) { return res.status(401).json({ error: 'authentication_required', message: 'Valid authentication is required' }); } const response = await this.getConversation(authReq); const responseData = await response.json(); res.status(response.status).json(responseData); }); // List conversations endpoint app.get('/api/conversations', async (req: any, res: any) => { const authReq = await this.authenticateCustomer(req); if (!authReq) { return res.status(401).json({ error: 'authentication_required', message: 'Valid authentication is required' }); } const response = await this.listConversations(authReq); const responseData = await response.json(); res.status(response.status).json(responseData); }); // Update conversation endpoint app.patch('/api/conversations/:id', async (req: any, res: any) => { const authReq = await this.authenticateCustomer(req); if (!authReq) { return res.status(401).json({ error: 'authentication_required', message: 'Valid authentication is required' }); } const response = await this.updateConversation(authReq); const responseData = await response.json(); res.status(response.status).json(responseData); }); } } export default EnhancedProxyController;