package handler

import (
	"net/http"

	"git.zkcoi.com/zkcoi/meshray/internal/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// SettingsHandler 系统设置 Handler
type SettingsHandler struct {
	logger          *zap.Logger
	settingsService *service.SettingsService
}

// NewSettingsHandler 创建系统设置 Handler
func NewSettingsHandler(settingsService *service.SettingsService, logger *zap.Logger) *SettingsHandler {
	return &SettingsHandler{
		logger:          logger,
		settingsService: settingsService,
	}
}

// GetSettings 获取系统设置
func (h *SettingsHandler) GetSettings(c *gin.Context) {
	setting, err := h.settingsService.GetSettings()
	if err != nil {
		h.logger.Error("获取系统设置失败", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "获取设置失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data": setting,
	})
}

// UpdateSettings 更新系统设置
func (h *SettingsHandler) UpdateSettings(c *gin.Context) {
	var updates map[string]interface{}
	if err := c.ShouldBindJSON(&updates); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "参数错误",
		})
		return
	}

	updatedSetting, err := h.settingsService.UpdateSettings(updates)
	if err != nil {
		h.logger.Error("更新系统设置失败", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "更新失败",
		})
		return
	}

	h.logger.Info("系统设置已更新", zap.Any("updates", updates))
	c.JSON(http.StatusOK, gin.H{
		"message": "设置已保存",
		"data":    updatedSetting,
	})
}
