/**
 * ElevenLabs Phone Configuration Service
 *
 * Configures Twilio native or custom SIP trunk via ElevenLabs PATCH /v1/convai/agents/{id}
 */

import { logger } from '@/lib/logger';
import { ElevenLabsServiceError } from './elevenlabs.service';
import type { PhoneConfig, PhoneProvisionResult } from '@/lib/types/voice-agent-phone.types';

export class ElevenLabsPhoneService {
  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;
  }

  /**
   * Configure phone/SIP on an ElevenLabs agent
   */
  async configurePhone(agentId: string, config: PhoneConfig): Promise<PhoneProvisionResult> {
    try {
      let platformSettings: Record<string, unknown>;

      if (config.connectionType === 'twilio_native' && config.twilio) {
        platformSettings = {
          phone: {
            provider: 'twilio',
            phone_number: config.twilio.twilioPhoneNumber,
            twilio: {
              account_sid: config.twilio.twilioAccountSid,
              auth_token: config.twilio.twilioAuthToken,
              phone_number: config.twilio.twilioPhoneNumber,
            },
          },
        };
      } else if (config.connectionType === 'custom_sip' && config.sip) {
        platformSettings = {
          overrides: {
            conversation: {
              sip_trunk_uri: config.sip.sipUri,
            },
          },
        };
      } else {
        return { success: false, error: 'Invalid phone configuration' };
      }

      logger.info('Configuring phone on ElevenLabs agent', {
        agentId,
        connectionType: config.connectionType,
      });

      const response = await fetch(`${this.baseUrl}/convai/agents/${agentId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'xi-api-key': this.getApiKey(),
        },
        body: JSON.stringify({ platform_settings: platformSettings }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        logger.error('Failed to configure phone on ElevenLabs agent', new Error(response.statusText), {
          status: response.status,
          agentId,
          errorData,
        });
        return {
          success: false,
          error: `ElevenLabs API error: ${response.status} ${response.statusText}`,
        };
      }

      const agent = await response.json();
      const sipEndpoint = config.connectionType === 'custom_sip'
        ? `sip:${agentId}@sip.elevenlabs.io`
        : undefined;

      logger.info('Successfully configured phone on ElevenLabs agent', { agentId });

      return {
        success: true,
        phoneId: agent.agent_id,
        sipEndpoint,
      };
    } catch (error) {
      logger.error('Error configuring phone', error);
      if (error instanceof ElevenLabsServiceError) throw error;
      return { success: false, error: 'Failed to configure phone' };
    }
  }

  /**
   * Remove phone configuration from agent
   */
  async removePhone(agentId: string): Promise<{ success: boolean; error?: string }> {
    try {
      const response = await fetch(`${this.baseUrl}/convai/agents/${agentId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'xi-api-key': this.getApiKey(),
        },
        body: JSON.stringify({
          platform_settings: {
            phone: null,
            overrides: null,
          },
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        return { success: false, error: `Failed to remove phone: ${response.statusText}` };
      }

      logger.info('Removed phone config from agent', { agentId });
      return { success: true };
    } catch (error) {
      logger.error('Error removing phone config', error);
      return { success: false, error: 'Failed to remove phone configuration' };
    }
  }
}

export const elevenLabsPhoneService = new ElevenLabsPhoneService();
