package plugins

import (
	"fmt"
	"kurumibot/database/mdb"
	"kurumibot/laniakea"
	"strings"
	"time"
)

func InitLogsPlugin() {}
func InitLogMiddleware() *laniakea.Middleware {
	middle := laniakea.NewMiddleware("LogMiddleware")
	middle = middle.SetExecutor(logMiddleware).SetAsync(true)
	return middle.Build()
}

func logMiddleware(ctx *laniakea.MsgContext, db *laniakea.DatabaseContext) {
	entry := &mdb.MessageLogEntry{
		MessageID: ctx.Msg.MessageID,
		SenderID:  ctx.FromID,
		ChatID:    ctx.Msg.Chat.ID,
		Text:      ctx.Msg.Text,
		TimeStamp: time.Now().Unix(),
	}
	err := mdb.WriteMessageLog(db, entry)
	if err != nil {
		fmt.Println(err)
	}
}
func DatabaseLogger(db *laniakea.DatabaseContext) laniakea.LoggerWriter {
	return func(level laniakea.LogLevel, prefix, traceback string, m []any) {
		t := time.Now()
		entry := &mdb.ConsoleLogEntry{
			Level:     level.GetName(),
			Prefix:    prefix,
			Traceback: traceback,
			Message: strings.Join(laniakea.Map(m, func(el any) string {
				return fmt.Sprintf("%v", el)
			}), "\n"),
			Time:      t,
			TimeStamp: t.Unix(),
		}
		err := mdb.WriteConsoleLog(db, entry)
		if err != nil {
			fmt.Println(err)
		}
	}
}
