import axios from 'axios';

export class TelegramClient {
  private url: string;

  constructor(token: string) {
    this.url = `https://api.telegram.org/bot${token}`;
  }

  async getMe() {
    return (await axios.get(`${this.url}/getMe`)).data.result;
  }

  async setWebhook(url: string) {
    return axios.post(`${this.url}/setWebhook`, { url, drop_pending_updates: true });
  }

  async sendMessage(chatId: number | string, text: string, options: any = {}) {
    try {
      return (await axios.post(`${this.url}/sendMessage`, { chat_id: chatId, text, ...options })).data;
    } catch (e: any) {
      console.error(`SendMsg Error: ${e.response?.data?.description || e.message}`);
    }
  }

  async sendVideo(chatId: number | string, video: string, options: any = {}) {
    try {
      return (await axios.post(`${this.url}/sendVideo`, { chat_id: chatId, video, ...options })).data;
    } catch (e: any) {
      console.error(`SendVideo Error: ${e.response?.data?.description || e.message}`);
    }
  }

  async editMessageText(chatId: number | string, messageId: number, text: string, options: any = {}) {
    try {
      return (await axios.post(`${this.url}/editMessageText`, { chat_id: chatId, message_id: messageId, text, ...options })).data;
    } catch (e: any) {
      console.error(`EditMsg Error: ${e.response?.data?.description || e.message}`);
    }
  }

  async deleteMessage(chatId: number | string, messageId: number) {
    try {
      await axios.post(`${this.url}/deleteMessage`, { chat_id: chatId, message_id: messageId });
    } catch (e) { /* ignore */ }
  }

  async answerCallbackQuery(id: string, text?: string) {
    try {
      await axios.post(`${this.url}/answerCallbackQuery`, { callback_query_id: id, text });
    } catch (e) { /* ignore */ }
  }
}
