package telegram

import (
	"jannex/telegram-bot-manager/modules/cache"
	"jannex/telegram-bot-manager/modules/database"
	"jannex/telegram-bot-manager/modules/logger"
	"jannex/telegram-bot-manager/modules/structs"
	"jannex/telegram-bot-manager/modules/utils"
	"regexp"
	"time"

	"git.ex.umbach.dev/Alex/roese-utils/rslogger"
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
	"github.com/rs/zerolog/log"
)

var bot *tgbotapi.BotAPI

func InitBot() {
	var err error

	bot, err = tgbotapi.NewBotAPI("6450280279:AAGxXdPv_YwRtl_pXIqYojqOecBrEjn3fJo")

	if err != nil {
		logger.AddSystemLog(rslogger.LogTypeError, "Failed to initialize Telegram bot, err: %v", err.Error())
		log.Fatal().Err(err).Msgf("Failed to initialize Telegram bot, err: %v", err.Error())
	}

	//bot.Debug = false

	logger.AddSystemLog(rslogger.LogTypeInfo, "Bot connected as %s", bot.Self.UserName)

	go IncomingMessagesHandler()
}

func IncomingMessagesHandler() {
	updateConfig := tgbotapi.NewUpdate(0)
	updateConfig.Timeout = 60

	updates, err := bot.GetUpdatesChan(updateConfig)

	if err != nil {
		logger.AddSystemLog(rslogger.LogTypeError, "Failed to get updates from Telegram bot, err: %v", err.Error())
		log.Fatal().Err(err).Msgf("Failed to get updates from Telegram bot, err: %v", err.Error())
	}

	for update := range updates {
		if update.Message == nil {
			continue
		}

		chatID := update.Message.Chat.ID
		text := update.Message.Text

		if text == "" {
			continue
		}

		regVerify := regexp.MustCompile(`/verify (\w+)`)
		regVerifyMatches := regVerify.FindStringSubmatch(text)

		regUnsubscribe := regexp.MustCompile(`/unsubscribe`)

		var replyMessage string

		if len(regVerifyMatches) == 2 {
			code := regVerifyMatches[1]

			if len(code) != utils.VerifyCodeLength {
				logger.AddSystemLog(rslogger.LogTypeWarning, "Received code with wrong length from user: %s %s. Message: %s", update.Message.From.FirstName, update.Message.From.LastName, code)
				continue
			}

			var userId string
			var ok bool

			if userId, ok = cache.GetTempVerifyByCode(code); !ok {
				// code not found in cache

				logger.AddSystemLog(rslogger.LogTypeWarning, "Received code which was not found in cache from user: %s %s. Message: %s", update.Message.From.FirstName, update.Message.From.LastName, code)

				replyMessage = "The code you entered is invalid. Please check the code and try again."
			} else {
				// code found in cache

				cache.RemoveTempVerifyCode(userId)

				var foundVerifiedUser structs.VerifiedUser

				res := database.DB.Where("chat_id = ?", update.Message.From.ID).First(&foundVerifiedUser)

				if res.Error != nil {
					logger.AddSystemLog(rslogger.LogTypeError, "Failed to get verified user from database, err: %v", res.Error.Error())
					continue
				}

				if foundVerifiedUser.UserId != "" {
					// user already verified

					replyMessage = "You have already verified your account. You will continue to receive notifications. Type /unsubscribe to stop receiving notifications."

					logger.AddSystemLog(rslogger.LogTypeWarning, "User: %s %s has tried to verify his account with code %s, but has already verified his account", update.Message.From.FirstName, update.Message.From.LastName, code)
				} else {
					// user not verified

					replyMessage = "You have successfully verified your account. You will now receive notifications. Type /unsubscribe to stop receiving notifications."

					database.DB.Create(&structs.VerifiedUser{
						UserId:    userId,
						ChatId:    update.Message.From.ID,
						CreatedAt: time.Now(),
					})

					logger.AddSystemLog(rslogger.LogTypeInfo, "User: %s %s has subscribed to receive notifications", update.Message.From.FirstName, update.Message.From.LastName)
				}
			}

			// reply to user
			reply := tgbotapi.NewMessage(chatID, replyMessage)

			_, err := bot.Send(reply)

			if err != nil {
				log.Error().Msgf("Failed to send subscribed reply to user, err: %v", err.Error())
				logger.AddSystemLog(rslogger.LogTypeError, "Failed to send reply to user, err: %v", err.Error())
			}
		} else if regUnsubscribe.MatchString(text) {
			res := database.DB.Delete(&structs.VerifiedUser{}, "chat_id = ?", update.Message.From.ID)

			if res.Error != nil {
				logger.AddSystemLog(rslogger.LogTypeError, "Failed to delete verified user from database, err: %v", res.Error.Error())
				continue
			}

			if res.RowsAffected == 0 {
				logger.AddSystemLog(rslogger.LogTypeWarning, "User: %s %s has tried to unsubscribe from receiving notifications, but has not been verified", update.Message.From.FirstName, update.Message.From.LastName)
				replyMessage = "You have not been verified yet. Type /verify <code> to start receiving notifications. The code can be found in the user profile on the dashboard."
			} else {
				logger.AddSystemLog(rslogger.LogTypeInfo, "User: %s %s has unsubscribed from receiving notifications", update.Message.From.FirstName, update.Message.From.LastName)
				replyMessage = "You have unsubscribed from receiving notifications. Type /verify <code> to start receiving notifications again. The code can be found in the user profile on the dashboard."
			}

			reply := tgbotapi.NewMessage(chatID, replyMessage)

			_, err := bot.Send(reply)

			if err != nil {
				logger.AddSystemLog(rslogger.LogTypeError, "Failed to send reply to user, err: %v", err.Error())
				log.Error().Msgf("Failed to send unsubscribed reply to user, err: %v", err.Error())
			}
		} else {
			logger.AddSystemLog(rslogger.LogTypeWarning, "Received unknown message: %s from user: %s %s", text, update.Message.From.FirstName, update.Message.From.LastName)
		}
	}
}
