package telegram

import (
	"fmt"
	"log"

	"github.com/Vomitblood/cspj-application/server/internal/log_backup"
	tg "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/studio-b12/gowebdav"
)

const (
	telegramToken  = "7215466800:AAGwjZnXEfbbjQiA0y7qtSzbSZNUWQJnyjo"
	telegramChatID = 622943829
)

type LogEntry struct {
	AuditData struct {
		Messages []string `json:"messages"`
	} `json:"audit_data"`
}

func Init(webdavClient *gowebdav.Client) *tg.BotAPI {
	bot, err := tg.NewBotAPI(telegramToken)
	if err != nil {
		log.Fatal("Failed to create Telegram bot:", err)
	}

	log.Println("Telegram bot connected")

	// send init message on startup
	testMsg := tg.NewMessage(telegramChatID, "I'm in")
	_, err = bot.Send(testMsg)
	if err != nil {
		log.Fatal("Failed to send test message:", err)
	}

	go handleUpdates(bot, webdavClient)

	return bot
}

// function to handle commands from user on tg
func handleUpdates(bot *tg.BotAPI, webdavClient *gowebdav.Client) {
	u := tg.NewUpdate(0)
	u.Timeout = 60
	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message != nil {
			command := update.Message.Text

			// /backup_logs
			if command == "/backup_logs" {
				err := log_backup.BackupLogs(webdavClient)
				if err != nil {
					sendTelegramResponse(bot, fmt.Sprintf("Failed to backup logs: %v", err))
				} else {
					sendTelegramResponse(bot, "Successfully backed up log files")
				}
			}

			// /restore_logs
			if command == "/restore_logs" {
				err := log_backup.RestoreLogs(webdavClient)
				if err != nil {
					sendTelegramResponse(bot, fmt.Sprintf("Failed to restore logs: %v", err))
				} else {
					sendTelegramResponse(bot, "Successfully restored log files")
				}
			}
		}
	}
}

func sendTelegramResponse(bot *tg.BotAPI, message string) {
	msg := tg.NewMessage(telegramChatID, message)
	_, err := bot.Send(msg)
	if err != nil {
		log.Println("Failed to send Telegram message:", err)
	}
}

func SendTelegramAlert(bot *tg.BotAPI, message string) {
	msg := tg.NewMessage(telegramChatID, fmt.Sprintf("🚨 *WEEWOO ALERT* 🚨\n%s", message))
	_, err := bot.Send(msg)
	if err != nil {
		log.Println("Failed to send Telegram message:", err)
	}
}
