package middleware

import (
	"bytes"
	"io/ioutil"
	"log"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
)

// OperationLogMiddleware 操作日志中间件
func OperationLogMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 开始时间
		startTime := time.Now()

		// 读取请求参数
		var requestBody []byte
		if c.Request.Method != "GET" {
			body, err := ioutil.ReadAll(c.Request.Body)
			if err != nil {
				log.Printf("Error reading request body: %v", err)
			} else {
				requestBody = body
				// 重置请求体，以便后续处理
				c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
			}
		}

		// 执行请求
		c.Next()

		// 结束时间
		endTime := time.Now()
		// 计算请求持续时间（毫秒）
		duration := int(endTime.Sub(startTime).Milliseconds())

		// 获取用户信息
		userID, exists := c.Get("userID")
		if !exists {
			return
		}

		username, _ := c.Get("username")

		// 构建操作日志
		operationLog := &models.OperationLog{
			UserID:   userID.(uint),
			Username: username.(string),
			IP:       c.ClientIP(),
			Path:     c.Request.URL.Path,
			Method:   c.Request.Method,
			Params:   string(requestBody),
			Status:   c.Writer.Status(),
			Duration: duration,
		}

		// 异步记录日志，避免影响响应
		go func() {
			if err := repositories.CreateOperationLog(operationLog); err != nil {
				log.Printf("Error creating operation log: %v", err)
			}
		}()
	}
}
