/**
 * ElevenLabs Conversations Service
 *
 * Fetches conversation history and transcripts from ElevenLabs API
 */

import { logger } from '@/lib/logger';

export interface ElevenLabsConversation {
  conversation_id: string;
  agent_id: string;
  status: string;
  start_time?: string;
  end_time?: string;
  metadata?: Record<string, unknown>;
}

export interface ElevenLabsConversationDetail extends ElevenLabsConversation {
  transcript?: Array<{
    role: string;
    message: string;
    timestamp?: number;
  }>;
  analysis?: {
    call_successful?: boolean;
    transcript_summary?: string;
  };
}

export class ElevenLabsConversationsService {
  private baseUrl = 'https://api.elevenlabs.io/v1';

  private getApiKey(): string {
    const apiKey = process.env.ELEVENLABS_API_KEY;
    if (!apiKey) throw new Error('ELEVENLABS_API_KEY environment variable is required');
    return apiKey;
  }

  /**
   * List conversations for an agent
   */
  async listConversations(agentId: string, params?: {
    page?: number;
    pageSize?: number;
  }): Promise<{ conversations: ElevenLabsConversation[]; total: number }> {
    try {
      const queryParams = new URLSearchParams();
      queryParams.set('agent_id', agentId);
      if (params?.page) queryParams.set('page', String(params.page));
      if (params?.pageSize) queryParams.set('page_size', String(params.pageSize));

      const response = await fetch(
        `${this.baseUrl}/convai/conversations?${queryParams.toString()}`,
        {
          headers: { 'xi-api-key': this.getApiKey() },
        }
      );

      if (!response.ok) {
        logger.error('Failed to list conversations', new Error(response.statusText));
        return { conversations: [], total: 0 };
      }

      const data = await response.json();
      return {
        conversations: data.conversations || [],
        total: data.total || 0,
      };
    } catch (error) {
      logger.error('Error listing conversations', error);
      return { conversations: [], total: 0 };
    }
  }

  /**
   * Get full conversation detail with transcript
   */
  async getConversation(conversationId: string): Promise<ElevenLabsConversationDetail | null> {
    try {
      const response = await fetch(
        `${this.baseUrl}/convai/conversations/${conversationId}`,
        {
          headers: { 'xi-api-key': this.getApiKey() },
        }
      );

      if (!response.ok) {
        logger.error('Failed to get conversation detail', new Error(response.statusText));
        return null;
      }

      return await response.json();
    } catch (error) {
      logger.error('Error getting conversation detail', error);
      return null;
    }
  }
}

export const elevenLabsConversationsService = new ElevenLabsConversationsService();
