package admin

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/service"

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

// SiteSettingController 站点设置控制器（仅 owner 可访问）
type SiteSettingController struct {
	settingService siteSettingUseCase
	defaults       *service.AuditDefaults
}

// NewSiteSettingController 构造函数
func NewSiteSettingController(settingService siteSettingUseCase, defaults *service.AuditDefaults) *SiteSettingController {
	return &SiteSettingController{settingService: settingService, defaults: defaults}
}

// SiteSettingsPage 站点设置管理页面
func (sc *SiteSettingController) SiteSettingsPage(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/site-settings/index.html", common.BuildAdminPageData(c, gin.H{
		"Title":   "站点设置",
		"ExtraCSS": "/admin/static/css/site-settings.css",
		"ExtraJS":  "/admin/static/js/site-settings.js",
	}))
}

// GetSettings 获取所有站点设置
func (sc *SiteSettingController) GetSettings(c *gin.Context) {
	all := sc.settingService.GetSettings()
	audit := sc.settingService.GetAuditSettings(sc.defaults)
	common.Ok(c, gin.H{
		"all":   all,
		"audit": audit,
	})
}

// UpdateSetting 更新单项设置
func (sc *SiteSettingController) UpdateSetting(c *gin.Context) {
	var req struct {
		Key   string `json:"key" binding:"required"`
		Value string `json:"value"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "参数错误")
		return
	}

	if err := sc.settingService.UpdateSetting(req.Key, req.Value); err != nil {
		common.Error(c, http.StatusInternalServerError, "保存失败")
		return
	}

	common.OkMessage(c, "设置已更新")
}

// UpdateBoolSetting 更新布尔设置
func (sc *SiteSettingController) UpdateBoolSetting(c *gin.Context) {
	var req struct {
		Key   string `json:"key" binding:"required"`
		Value string `json:"value" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "参数错误")
		return
	}

	v, err := service.ParseBool(req.Value)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "值必须为 true 或 false")
		return
	}

	if err := sc.settingService.UpdateBoolSetting(req.Key, v); err != nil {
		common.Error(c, http.StatusInternalServerError, "保存失败")
		return
	}

	common.OkMessage(c, "设置已更新")
}

// GetBoolSetting 获取单个布尔设置的当前值
func (sc *SiteSettingController) GetBoolSetting(c *gin.Context) {
	key := c.Query("key")
	if key == "" {
		common.Error(c, http.StatusBadRequest, "缺少 key 参数")
		return
	}

	defaultVal := c.DefaultQuery("default", "false")
	d, _ := strconv.ParseBool(defaultVal)

	val := sc.settingService.GetAuditSettings(sc.defaults)
	// 简单键值查找
	switch key {
	case "audit.enabled":
		common.Ok(c, gin.H{"value": val.Enabled})
	case "audit.username_audit":
		common.Ok(c, gin.H{"value": val.UsernameAudit})
	case "audit.avatar_audit":
		common.Ok(c, gin.H{"value": val.AvatarAudit})
	case "audit.bio_audit":
		common.Ok(c, gin.H{"value": val.BioAudit})
	default:
		common.Ok(c, gin.H{"value": d})
	}
}
