package handlers

import (
	"net/http"

	"veza-backend-api/internal/metrics"

	"github.com/gin-gonic/gin"
)

// ErrorMetricsInterface defines methods needed for aggregated metrics handler
type ErrorMetricsInterface interface {
	GetAggregatedMetrics() *metrics.AggregatedMetrics
}

// AggregatedMetricsHandler gère l'exposition des métriques agrégées
type AggregatedMetricsHandler struct {
	errorMetrics ErrorMetricsInterface
}

// NewAggregatedMetricsHandler crée un nouveau handler pour les métriques agrégées
func NewAggregatedMetricsHandler(errorMetrics *metrics.ErrorMetrics) *AggregatedMetricsHandler {
	return &AggregatedMetricsHandler{
		errorMetrics: errorMetrics,
	}
}

// NewAggregatedMetricsHandlerWithInterface creates a new handler with interface (for testing)
func NewAggregatedMetricsHandlerWithInterface(errorMetrics ErrorMetricsInterface) *AggregatedMetricsHandler {
	return &AggregatedMetricsHandler{
		errorMetrics: errorMetrics,
	}
}

// GetAggregated expose les métriques agrégées
// Endpoint: GET /metrics/aggregated?window=1m|5m|1h
// Si window n'est pas spécifié, retourne toutes les fenêtres
func (h *AggregatedMetricsHandler) GetAggregated(c *gin.Context) {
	if h.errorMetrics == nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Metrics not available",
		})
		return
	}

	aggregatedMetrics := h.errorMetrics.GetAggregatedMetrics()
	if aggregatedMetrics == nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Aggregated metrics not available",
		})
		return
	}

	windowType := c.Query("window")

	if windowType != "" {
		// Retourner une seule fenêtre
		validWindows := []string{"1m", "5m", "1h"}
		isValid := false
		for _, w := range validWindows {
			if windowType == w {
				isValid = true
				break
			}
		}

		if !isValid {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "Invalid window type. Valid values: 1m, 5m, 1h",
			})
			return
		}

		windows := aggregatedMetrics.GetAggregated(windowType)
		c.JSON(http.StatusOK, gin.H{
			"window":  windowType,
			"windows": windows,
		})
	} else {
		// Retourner toutes les fenêtres
		allWindows := aggregatedMetrics.GetAllAggregated()
		c.JSON(http.StatusOK, gin.H{
			"windows": allWindows,
		})
	}
}

// AggregatedMetrics expose les métriques agrégées (fonction helper pour routes simples)
func AggregatedMetrics(errorMetrics *metrics.ErrorMetrics) gin.HandlerFunc {
	handler := NewAggregatedMetricsHandler(errorMetrics)
	return handler.GetAggregated
}

// AggregatedMetricsWithInterface expose les métriques agrégées avec interface (pour tests)
func AggregatedMetricsWithInterface(errorMetrics ErrorMetricsInterface) gin.HandlerFunc {
	handler := NewAggregatedMetricsHandlerWithInterface(errorMetrics)
	return handler.GetAggregated
}
