package api

import (
	"net/http"
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/wormhole/wormhole/internal/auth"
	"github.com/wormhole/wormhole/internal/config"
)

func (s *Server) getSettings(c *gin.Context) {
	claims := getClaims(c)
	if !auth.IsAdmin(claims.Role) {
		c.JSON(http.StatusForbidden, gin.H{"error": "admin only"})
		return
	}
	dto := s.cfg.ToDTO()
	c.JSON(http.StatusOK, gin.H{
		"settings": dto,
		"note":     "修改监听端口后需重启 wormhole server 生效",
	})
}

func (s *Server) updateSettings(c *gin.Context) {
	claims := getClaims(c)
	if !auth.IsAdmin(claims.Role) {
		c.JSON(http.StatusForbidden, gin.H{"error": "admin only"})
		return
	}
	var req config.SettingsDTO
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	oldServer := s.cfg.Server
	newCfg := config.SettingsFromDTO(req, s.cfg)
	if err := s.store.SaveConfig(newCfg); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	*s.cfg = *newCfg
	s.auth.ReloadAuth(&s.cfg.Auth)
	s.resAuth.ReloadAuth(&s.cfg.Auth)

	restartRequired := !reflect.DeepEqual(oldServer, s.cfg.Server) ||
		oldServer.TLSCertFile != s.cfg.Server.TLSCertFile ||
		oldServer.TLSKeyFile != s.cfg.Server.TLSKeyFile

	c.JSON(http.StatusOK, gin.H{
		"settings":         s.cfg.ToDTO(),
		"restart_required": restartRequired,
	})
}
