import TelegramBot from "node-telegram-bot-api";

let bot: TelegramBot | null = null;

export function getTelegramBot(): TelegramBot | null {
  if (bot) return bot;

  const token = process.env.TELEGRAM_BOT_TOKEN;

  if (!token) {
    console.warn("TELEGRAM_BOT_TOKEN not provided. Telegram functionality will be disabled.");
    return null;
  }

  bot = new TelegramBot(token, { polling: false });
  return bot;
}

export async function sendTelegramMessage(chatId: number, message: string): Promise<boolean> {
  const telegramBot = getTelegramBot();

  if (!telegramBot) {
    console.error("Telegram bot not initialized");
    return false;
  }

  try {
    await telegramBot.sendMessage(chatId, message, {
      parse_mode: "HTML",
    });
    return true;
  } catch (error) {
    console.error("Failed to send Telegram message:", error);
    return false;
  }
}

export async function sendBulkTelegramMessages(
  chatIds: number[],
  message: string
): Promise<{ sent: number; failed: number }> {
  let sent = 0;
  let failed = 0;

  for (const chatId of chatIds) {
    const success = await sendTelegramMessage(chatId, message);
    if (success) {
      sent++;
    } else {
      failed++;
    }
    await new Promise((resolve) => setTimeout(resolve, 50));
  }

  return { sent, failed };
}
