package api import ( "net/http" "strings" "time" "github.com/ez-api/ez-api/internal/model" "github.com/gin-gonic/gin" "gorm.io/gorm" ) type InternalHandler struct { db *gorm.DB } func NewInternalHandler(db *gorm.DB) *InternalHandler { return &InternalHandler{db: db} } type statsFlushRequest struct { Keys []statsFlushEntry `json:"keys"` } type statsFlushEntry struct { TokenHash string `json:"token_hash"` Requests int64 `json:"requests"` Tokens int64 `json:"tokens"` LastAccessedAt int64 `json:"last_accessed_at"` } func (h *InternalHandler) FlushStats(c *gin.Context) { if h == nil || h.db == nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "database not configured"}) return } var req statsFlushRequest if err := c.ShouldBindJSON(&req); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"}) return } if len(req.Keys) == 0 { c.JSON(http.StatusOK, gin.H{"updated": 0}) return } updated := 0 err := h.db.Transaction(func(tx *gorm.DB) error { for _, entry := range req.Keys { hash := strings.TrimSpace(entry.TokenHash) if hash == "" { continue } if entry.Requests < 0 || entry.Tokens < 0 || entry.LastAccessedAt < 0 { return gorm.ErrInvalidData } updates := map[string]any{} if entry.Requests > 0 { updates["request_count"] = gorm.Expr("request_count + ?", entry.Requests) } if entry.Tokens > 0 { updates["used_tokens"] = gorm.Expr("used_tokens + ?", entry.Tokens) updates["quota_used"] = gorm.Expr("CASE WHEN quota_limit >= 0 THEN quota_used + ? ELSE quota_used END", entry.Tokens) } if entry.LastAccessedAt > 0 { accessTime := time.Unix(entry.LastAccessedAt, 0).UTC() updates["last_accessed_at"] = gorm.Expr("CASE WHEN last_accessed_at IS NULL OR last_accessed_at < ? THEN ? ELSE last_accessed_at END", accessTime, accessTime) } if len(updates) == 0 { continue } res := tx.Model(&model.Key{}).Where("token_hash = ?", hash).Updates(updates) if res.Error != nil { return res.Error } if res.RowsAffected > 0 { updated++ } } return nil }) if err != nil { if err == gorm.ErrInvalidData { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid stats payload"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to flush stats", "details": err.Error()}) return } c.JSON(http.StatusOK, gin.H{"updated": updated}) }