package senders

import (
	"fmt"
	"gopkg.in/tucnak/telebot.v2"
	"strconv"
	"time"
)

type TgSender struct {
	bot *telebot.Bot
}

func NewTgSender(tgToken string) (*TgSender, error) {
	bot, err := telebot.NewBot(telebot.Settings{
		Token:  tgToken,
		Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
	})

	if err != nil {
		return nil, fmt.Errorf("error creating Telegram bot: %w", err)
	}

	return &TgSender{bot: bot}, nil
}

func (tg *TgSender) SendLead(data LeadData) error {
	text, err := generateTextFromTemplate(data.TemplateData, data.Template)
	if err != nil {
		return err
	}

	chatStr := data.To.(string)

	chat, err := strconv.ParseInt(chatStr, 10, 64)
	if err != nil {
		return err
	}
	_, err = tg.bot.Send(telebot.ChatID(chat), text, &telebot.SendOptions{
		ParseMode: telebot.ModeHTML,
	})
	if err != nil {
		return fmt.Errorf("error sending Telegram message: %w", err)
	}

	return nil
}

func (tg *TgSender) Name() string {
	return "telegram"
}
