package dblogger

import (
	"fmt"
	"log"
	"time"

	"bindbox-game/internal/proposal"
	"bindbox-game/internal/repository/mysql"
	"bindbox-game/internal/repository/mysql/dao"
	"bindbox-game/internal/repository/mysql/model"

	"github.com/spf13/cast"
)

func LoggerHandler(db mysql.Repo) func(msg *proposal.RequestLoggerMessage) {
	return func(msg *proposal.RequestLoggerMessage) {
		logData := new(model.LogRequest)
		logData.Tid = msg.Tid
		logData.Username = msg.Username
		logData.Host = msg.HOST
		logData.Path = msg.Path
		logData.Method = msg.Method
		logData.HTTPCode = int32(msg.HTTPCode)
		logData.BusinessCode = int32(msg.BusinessCode)
		logData.CostMilliseconds = float64(cast.ToFloat32(fmt.Sprintf("%.2f", msg.CostSeconds*1000)))
		logData.IsSuccess = -1
		if msg.IsSuccess == true {
			logData.IsSuccess = 1
		}
		logData.Content = msg.Content
		logData.CreatedAt = time.Now()

		if err := dao.Use(db.GetDbW()).LogRequest.Create(logData); err != nil {
			log.Println(fmt.Sprintf("日志写入失败: %s", err.Error()))
		}
	}
}
