package service

import (
	"strconv"
)

// siteSettingsManager 站点设置服务所需的最小接口（ISP）
type siteSettingsManager interface {
	Get(key, defaultVal string) string
	GetBool(key string, defaultVal bool) bool
	Set(key, value string) error
	SetBool(key string, value bool) error
	All() map[string]string
}

// SiteSettingService 站点设置业务逻辑
type SiteSettingService struct {
	settings siteSettingsManager
}

// NewSiteSettingService 构造函数
func NewSiteSettingService(settings siteSettingsManager) *SiteSettingService {
	return &SiteSettingService{settings: settings}
}

// GetSettings 获取所有站点设置（仅 owner 可见）
func (s *SiteSettingService) GetSettings() map[string]string {
	return s.settings.All()
}

// UpdateSetting 更新单项设置
func (s *SiteSettingService) UpdateSetting(key, value string) error {
	return s.settings.Set(key, value)
}

// UpdateBoolSetting 更新布尔设置
func (s *SiteSettingService) UpdateBoolSetting(key string, value bool) error {
	return s.settings.SetBool(key, value)
}

// GetBool gets a boolean setting with a default
func (s *SiteSettingService) GetBool(key string, defaultVal bool) bool {
	return s.settings.GetBool(key, defaultVal)
}

// --- 审核相关设置快捷方法 ---

// AuditSettings 审核相关站点设置集合（用于前端展示）
type AuditSettings struct {
	Enabled       bool `json:"enabled"`
	UsernameAudit bool `json:"username_audit"`
	AvatarAudit   bool `json:"avatar_audit"`
	BioAudit      bool `json:"bio_audit"`
}

// GetAuditSettings 获取审核相关设置
func (s *SiteSettingService) GetAuditSettings(defaultCfg *AuditDefaults) *AuditSettings {
	return &AuditSettings{
		Enabled:       s.settings.GetBool("audit.enabled", defaultCfg.Enabled),
		UsernameAudit: s.settings.GetBool("audit.username_audit", defaultCfg.UsernameAudit),
		AvatarAudit:   s.settings.GetBool("audit.avatar_audit", defaultCfg.AvatarAudit),
		BioAudit:      s.settings.GetBool("audit.bio_audit", defaultCfg.BioAudit),
	}
}

// AuditDefaults config.yaml 中的审核默认值
type AuditDefaults struct {
	Enabled       bool
	UsernameAudit bool
	AvatarAudit   bool
	BioAudit      bool
}

// GetBoolSetting is a generic getter used by controllers
func (s *SiteSettingService) GetBoolSetting(key string, defaultVal bool) bool {
	return s.settings.GetBool(key, defaultVal)
}

// ParseBool 解析字符串为布尔值
func ParseBool(v string) (bool, error) {
	return strconv.ParseBool(v)
}
