import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import {
  ChannelAdapterPort,
  SendMessageParams,
  DeliveryResult,
} from '../../domain/ports/outbound/channel-adapter.port';
import { ChannelType } from '../../domain/value-objects/channel-type.vo';
import { randomUUID } from 'crypto';

@Injectable()
export class VoiceServiceClientAdapter implements ChannelAdapterPort {
  private readonly logger = new Logger(VoiceServiceClientAdapter.name);
  readonly channelType = ChannelType.VOICE_DIALOG;

  constructor(private readonly config: ConfigService) {}

  async send(params: SendMessageParams): Promise<DeliveryResult> {
    const baseUrl = this.config.get<string>('VOICE_SERVICE_URL');

    try {
      const response = await fetch(`${baseUrl}/api/v1/calls`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          phone: params.to.phone,
          ttsText: params.ttsText ?? params.content,
          priority: params.priority,
          contactId: params.to.id,
          approvalAction: params.approvalAction,
        }),
      });

      if (!response.ok) {
        const errorData = await response.text();
        throw new Error(`Voice service error: ${response.status} ${errorData}`);
      }

      const data = await response.json();
      return { messageId: data.callId ?? randomUUID(), status: 'sent' };
    } catch (error) {
      this.logger.error('Voice service call failed', error);
      return {
        messageId: randomUUID(),
        status: 'failed',
        error: error instanceof Error ? error.message : 'Voice service call failed',
      };
    }
  }

  async isAvailable(): Promise<boolean> {
    return !!this.config.get('VOICE_SERVICE_URL');
  }
}
