package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"veza-backend-api/internal/config"
)

// ConfigReloaderInterface defines methods needed for config reload handler
type ConfigReloaderInterface interface {
	ReloadAll() error
	ReloadLogLevel() error
	ReloadRateLimits() error
	GetCurrentConfig() *config.ReloadableConfig
}

// ConfigReloadHandler gère les endpoints de rechargement de configuration (T0034)
type ConfigReloadHandler struct {
	reloader      ConfigReloaderInterface
	logger        *zap.Logger
	commonHandler *CommonHandler
}

// NewConfigReloadHandler crée un nouveau handler pour le rechargement de configuration
func NewConfigReloadHandler(reloader *config.ConfigReloader, logger *zap.Logger) *ConfigReloadHandler {
	return &ConfigReloadHandler{
		reloader:      reloader,
		logger:        logger,
		commonHandler: NewCommonHandler(logger),
	}
}

// NewConfigReloadHandlerWithInterface creates a new config reload handler with interface (for testing)
func NewConfigReloadHandlerWithInterface(reloader ConfigReloaderInterface, logger *zap.Logger) *ConfigReloadHandler {
	return &ConfigReloadHandler{
		reloader:      reloader,
		logger:        logger,
		commonHandler: NewCommonHandler(logger),
	}
}

// ReloadConfig gère le rechargement de toute la configuration (T0034)
func (h *ConfigReloadHandler) ReloadConfig() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req struct {
			Type string `json:"type"` // "all", "log_level", "rate_limits"
		}

		if appErr := h.commonHandler.BindAndValidateJSON(c, &req); appErr != nil {
			// Si pas de JSON valide, recharger tout par défaut
			req.Type = "all"
		}

		var err error
		var message string

		switch req.Type {
		case "log_level":
			err = h.reloader.ReloadLogLevel()
			message = "Log level reloaded successfully"
		case "rate_limits":
			err = h.reloader.ReloadRateLimits()
			message = "Rate limits reloaded successfully"
		case "all", "":
			err = h.reloader.ReloadAll()
			message = "All configurations reloaded successfully"
		default:
			c.JSON(http.StatusBadRequest, gin.H{
				"error": "Invalid reload type. Use 'all', 'log_level', or 'rate_limits'",
			})
			return
		}

		if err != nil {
			h.logger.Error("Failed to reload configuration", zap.Error(err), zap.String("type", req.Type))
			c.JSON(http.StatusInternalServerError, gin.H{
				"error":   "Failed to reload configuration",
				"details": err.Error(),
			})
			return
		}

		// Récupérer la configuration actuelle pour la réponse
		currentConfig := h.reloader.GetCurrentConfig()

		RespondSuccess(c, http.StatusOK, gin.H{
			"message": message,
			"config":  currentConfig,
		})
	}
}

// GetConfig gère la récupération de la configuration actuelle (T0034)
func (h *ConfigReloadHandler) GetConfig() gin.HandlerFunc {
	return func(c *gin.Context) {
		currentConfig := h.reloader.GetCurrentConfig()
		RespondSuccess(c, http.StatusOK, gin.H{
			"config": currentConfig,
		})
	}
}
