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 TelegramAdapter implements ChannelAdapterPort {
  private readonly logger = new Logger(TelegramAdapter.name);
  readonly channelType = ChannelType.TELEGRAM;

  constructor(private readonly config: ConfigService) {}

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

    try {
      const url = `https://api.telegram.org/bot${botToken}/sendMessage`;

      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: params.to.telegramId,
          text: params.content,
          parse_mode: 'HTML',
        }),
      });

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

      const data = await response.json();
      return {
        messageId: data.result?.message_id?.toString() ?? randomUUID(),
        status: 'sent',
      };
    } catch (error) {
      this.logger.error('Telegram send failed', error);
      return {
        messageId: randomUUID(),
        status: 'failed',
        error: error instanceof Error ? error.message : 'Telegram send failed',
      };
    }
  }

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