package initialize

import (
	"context"
	"fmt"

	"github.com/perfect-panel/server/pkg/logger"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/perfect-panel/server/internal/logic/telegram"
	"github.com/perfect-panel/server/internal/model/auth"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/tool"
)

func Telegram(svc *svc.ServiceContext) {
	if !svc.Config.Telegram.Enable {
		logger.Info("Telegram disabled, skipping initialization")
		return
	}

	// Prefer BotToken from DB auth method, fallback to config file
	var usedToken string
	var webHookDomain string
	method, err := svc.AuthModel.FindOneByMethod(context.Background(), "telegram")
	if err == nil {
		tgConfig := new(auth.TelegramAuthConfig)
		if err = tgConfig.Unmarshal(method.Config); err == nil {
			usedToken = tgConfig.BotToken
			webHookDomain = tgConfig.WebHookDomain
		} else {
			logger.Errorf("[Init Telegram Config] Unmarshal Telegram Config Error: %s", err.Error())
		}
	} else {
		logger.Debugf("[Init Telegram Config] No Telegram method in DB, fallback to file config: %s", err.Error())
	}
	if usedToken == "" {
		usedToken = svc.Config.Telegram.BotToken
	}
	if webHookDomain == "" {
		webHookDomain = svc.Config.Telegram.WebHookDomain
	}
	if usedToken == "" {
		logger.Debug("[Init Telegram Config] Telegram Token is empty")
		return
	}

	bot, err := tgbotapi.NewBotAPI(usedToken)
	if err != nil {
		logger.Error("[Init Telegram Config] New Bot API Error: ", logger.Field("error", err.Error()))
		return
	}

	if webHookDomain == "" || svc.Config.Debug {
		// Ensure webhook is removed to avoid long polling conflict
		if _, derr := bot.MakeRequest("deleteWebhook", tgbotapi.Params{}); derr != nil {
			logger.Errorf("[Init Telegram Config] Delete webhook failed: %s", derr.Error())
		}
		// Long Polling mode
		updateConfig := tgbotapi.NewUpdate(0)
		updateConfig.Timeout = 60
		updates := bot.GetUpdatesChan(updateConfig)
		go func() {
			for update := range updates {
				if update.Message != nil {
					ctx := context.Background()
					l := telegram.NewTelegramLogic(ctx, svc)
					l.TelegramLogic(&update)
				}
			}
		}()
	} else {
		wh, err := tgbotapi.NewWebhook(fmt.Sprintf("%s/v1/telegram/webhook?secret=%s", webHookDomain, tool.Md5Encode(usedToken, false)))
		if err != nil {
			logger.Errorf("[Init Telegram Config] New Webhook Error: %s", err.Error())
			return
		}
		_, err = bot.Request(wh)
		if err != nil {
			logger.Errorf("[Init Telegram Config] Request Webhook Error: %s", err.Error())
			return
		}
	}

	user, err := bot.GetMe()
	if err != nil {
		logger.Error("[Init Telegram Config] Get Bot Info Error: ", logger.Field("error", err.Error()))
		return
	}
	svc.Config.Telegram.BotID = user.ID
	svc.Config.Telegram.BotName = user.UserName
	svc.Config.Telegram.BotToken = usedToken
	svc.Config.Telegram.WebHookDomain = webHookDomain
	svc.TelegramBot = bot

	if webHookDomain == "" || svc.Config.Debug {
		logger.Info("[Init Telegram Config] Long polling mode initialized")
	} else {
		logger.Info("[Init Telegram Config] Webhook set success")
	}
}
