/**
 * ElevenLabs Agent Authentication Service
 *
 * Handles signed URL generation and domain allowlisting for widget security.
 */

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

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

  /**
   * Generate a signed URL for authenticated widget access
   */
  async generateSignedUrl(
    agentId: string,
    _expiresIn?: number
  ): Promise<{ signedUrl: string } | { error: string }> {
    try {
      logger.info('Generating signed URL', { agentId });

      const response = await fetch(
        `${this.baseUrl}/convai/conversation/get_signed_url?agent_id=${agentId}`,
        {
          method: 'GET',
          headers: {
            'xi-api-key': this.getApiKey(),
          },
        }
      );

      if (!response.ok) {
        return { error: `Failed to generate signed URL: ${response.statusText}` };
      }

      const data = await response.json();
      return { signedUrl: data.signed_url };
    } catch (error) {
      logger.error('Error generating signed URL', error);
      return { error: 'Failed to generate signed URL' };
    }
  }

  /**
   * Set domain allowlist for an agent's widget
   */
  async setDomainAllowlist(
    agentId: string,
    domains: string[]
  ): Promise<{ success: boolean; error?: string }> {
    try {
      logger.info('Setting domain allowlist', { agentId, domains });

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

      if (!response.ok) {
        return { success: false, error: `Failed to set domain allowlist: ${response.statusText}` };
      }

      return { success: true };
    } catch (error) {
      logger.error('Error setting domain allowlist', error);
      return { success: false, error: 'Failed to set domain allowlist' };
    }
  }

  /**
   * Get domain allowlist for an agent
   */
  async getDomainAllowlist(
    agentId: string
  ): Promise<{ domains: string[] } | { error: string }> {
    try {
      const response = await fetch(`${this.baseUrl}/convai/agents/${agentId}`, {
        method: 'GET',
        headers: {
          'xi-api-key': this.getApiKey(),
        },
      });

      if (!response.ok) {
        return { error: `Failed to fetch agent: ${response.statusText}` };
      }

      const data = await response.json();
      const domains = data.platform_settings?.widget?.allowed_origins || [];
      return { domains };
    } catch (error) {
      logger.error('Error fetching domain allowlist', error);
      return { error: 'Failed to fetch domain allowlist' };
    }
  }
}

export const elevenLabsAuthService = new ElevenLabsAuthService();
