package service

import (
	"strconv"
	"strings"
	"xboard-go/internal/config"
	"xboard-go/internal/database"
	"xboard-go/internal/model"
)

func GetSetting(name string) (string, bool) {
	var setting model.Setting
	if err := database.DB.Select("value").Where("name = ?", name).First(&setting).Error; err != nil {
		return "", false
	}

	return setting.Value, true
}

func MustGetString(name, defaultValue string) string {
	value, ok := GetSetting(name)
	if !ok || strings.TrimSpace(value) == "" {
		return defaultValue
	}
	return value
}

func MustGetInt(name string, defaultValue int) int {
	value, ok := GetSetting(name)
	if !ok {
		return defaultValue
	}

	parsed, err := strconv.Atoi(strings.TrimSpace(value))
	if err != nil {
		return defaultValue
	}
	return parsed
}

func MustGetBool(name string, defaultValue bool) bool {
	value, ok := GetSetting(name)
	if !ok {
		return defaultValue
	}

	switch strings.ToLower(strings.TrimSpace(value)) {
	case "1", "true", "yes", "on":
		return true
	case "0", "false", "no", "off":
		return false
	default:
		return defaultValue
	}
}

func GetAdminSecurePath() string {
	if securePath := strings.Trim(MustGetString("secure_path", ""), "/"); securePath != "" {
		return securePath
	}
	if frontendPath := strings.Trim(MustGetString("frontend_admin_path", ""), "/"); frontendPath != "" {
		return frontendPath
	}
	return "admin"
}

func GetAppURL() string {
	if appURL := strings.TrimSpace(MustGetString("app_url", "")); appURL != "" {
		return strings.TrimRight(appURL, "/")
	}
	return strings.TrimRight(config.AppConfig.AppURL, "/")
}
