// file: gemini-balancer\internal\handlers\setting_handler.go
package handlers

import (
	"gemini-balancer/internal/errors"
	"gemini-balancer/internal/response"
	"gemini-balancer/internal/settings"

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

type SettingHandler struct {
	settingsManager *settings.SettingsManager
}

func NewSettingHandler(settingsManager *settings.SettingsManager) *SettingHandler {
	return &SettingHandler{settingsManager: settingsManager}
}
func (h *SettingHandler) GetSettings(c *gin.Context) {
	settings := h.settingsManager.GetSettings()
	response.Success(c, settings)
}
func (h *SettingHandler) UpdateSettings(c *gin.Context) {
	var newSettingsMap map[string]interface{}
	if err := c.ShouldBindJSON(&newSettingsMap); err != nil {
		logrus.WithError(err).Error("Failed to bind JSON in UpdateSettings")
		response.Error(c, errors.NewAPIError(errors.ErrInvalidJSON, "Invalid JSON: "+err.Error()))
		return
	}

	logrus.Debugf("Received settings update: %+v", newSettingsMap)

	validKeys := make(map[string]interface{})
	for key, value := range newSettingsMap {
		if _, exists := h.settingsManager.IsValidKey(key); exists {
			validKeys[key] = value
		} else {
			logrus.Warnf("Invalid key received: %s", key)
		}
	}

	if len(validKeys) == 0 {
		response.Error(c, errors.NewAPIError(errors.ErrInvalidJSON, "No valid settings keys provided"))
		return
	}

	logrus.Debugf("Valid keys to update: %+v", validKeys)

	if err := h.settingsManager.UpdateSettings(validKeys); err != nil {
		logrus.WithError(err).Error("Failed to update settings")
		response.Error(c, errors.NewAPIError(errors.ErrInternalServer, err.Error()))
		return
	}
	response.Success(c, gin.H{"message": "Settings updated successfully"})
}

// ResetSettingsToDefaults resets all settings to their default values
func (h *SettingHandler) ResetSettingsToDefaults(c *gin.Context) {
	defaultSettings, err := h.settingsManager.ResetAndSaveSettings()
	if err != nil {
		response.Error(c, errors.NewAPIError(errors.ErrInternalServer, "Failed to reset settings: "+err.Error()))
		return
	}
	response.Success(c, defaultSettings)
}
