package middleware

import (
	"net/http"
	"strings"
	"time"

	"github.com/ez-api/ez-api/internal/model"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// OperationLogMiddleware records admin mutating operations.
func OperationLogMiddleware(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()

		if db == nil {
			return
		}
		switch c.Request.Method {
		case http.MethodGet, http.MethodHead, http.MethodOptions:
			return
		}

		errMsg := ""
		if len(c.Errors) > 0 {
			errMsg = c.Errors.String()
		}
		reqID := ""
		if v, ok := c.Get("request_id"); ok {
			if s, ok := v.(string); ok {
				reqID = s
			}
		}

		log := model.OperationLog{
			Actor:        "admin",
			Method:       c.Request.Method,
			Path:         c.Request.URL.Path,
			Query:        strings.TrimSpace(c.Request.URL.RawQuery),
			StatusCode:   c.Writer.Status(),
			LatencyMs:    time.Since(start).Milliseconds(),
			ClientIP:     c.ClientIP(),
			RequestID:    reqID,
			UserAgent:    c.GetHeader("User-Agent"),
			ErrorMessage: errMsg,
		}
		_ = db.Create(&log).Error
	}
}
