import {
  sendTelegramMessageEvent,
  type SendTelegramMessageEvent,
  type TelegramPlugin
} from '@profitsniper/shared'
import telegramBot from 'node-telegram-bot-api'
import log from 'loglevel'
import stringify from 'fast-safe-stringify'

const isDev = process.env.NODE_ENV === 'development'

log.setLevel(isDev ? 'debug' : 'error')

const bots = new Map<string, telegramBot>()

const createTelegramBot = ({
  botToken
}: SendTelegramMessageEvent): telegramBot => {
  if (bots.has(botToken)) {
    return bots.get(botToken) as telegramBot
  }

  const bot = new telegramBot(botToken)

  bots.set(botToken, bot)

  bot.on('polling_error', (error) => {
    log.error(`Telegram polling error: ${stringify(error)}`)
  })

  return bot
}

const sendMessage: TelegramPlugin = async (event: SendTelegramMessageEvent) => {
  try {
    sendTelegramMessageEvent.parse(event)
    const { chatId, message } = event

    const tg = createTelegramBot(event)

    const msg = await tg.sendMessage(chatId, message)

    return {
      message_id: msg.message_id,
      success: true,
      date: msg.date
    }
  } catch (error) {
    log.error(`Telegram error: ${stringify(error)}`)

    return { error: stringify(error) }
  }
}

export default sendMessage
