import axios from 'axios'

export interface TelegramConfig {
  botToken: string
  chatId: string
}

export class TelegramBot {
  private config: TelegramConfig
  private baseUrl: string

  constructor(config: TelegramConfig) {
    this.config = config
    this.baseUrl = `https://api.telegram.org/bot${config.botToken}`
  }

  updateConfig(config: TelegramConfig): void {
    this.config = config
    this.baseUrl = `https://api.telegram.org/bot${config.botToken}`
  }

  async sendMessage(text: string, parseMode: 'Markdown' | 'HTML' = 'Markdown'): Promise<boolean> {
    if (!this.config.botToken || !this.config.chatId) {
      console.warn('Telegram bot not configured')
      return false
    }

    try {
      await axios.post(`${this.baseUrl}/sendMessage`, {
        chat_id: this.config.chatId,
        text,
        parse_mode: parseMode,
        disable_web_page_preview: true
      }, {
        timeout: 10000
      })
      return true
    } catch (error) {
      console.error('Failed to send Telegram message:', error)
      return false
    }
  }

  async sendAlert(title: string, message: string): Promise<boolean> {
    const formattedMessage = `*${this.escapeMarkdown(title)}*\n\n${this.escapeMarkdown(message)}`
    return this.sendMessage(formattedMessage)
  }

  async testConnection(): Promise<{ success: boolean; error?: string }> {
    if (!this.config.botToken) {
      return { success: false, error: 'Bot token not configured' }
    }

    try {
      const response = await axios.get(`${this.baseUrl}/getMe`, { timeout: 10000 })
      if (response.data.ok) {
        return { success: true }
      }
      return { success: false, error: 'Invalid bot token' }
    } catch (error) {
      return { success: false, error: (error as Error).message }
    }
  }

  private escapeMarkdown(text: string): string {
    return text.replace(/[_*[\]()~`>#+=|{}.!-]/g, '\\$&')
  }
}

