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
	res := database.DB.Select("value").Where("name = ?", name).Limit(1).Find(&setting)
	if res.Error != nil || res.RowsAffected == 0 {
		return "", false
	}

	return setting.Value, true
}

func normalizeWrappedString(value string) string {
	value = strings.TrimSpace(value)
	for len(value) >= 2 {
		first := value[0]
		last := value[len(value)-1]
		if (first == '"' && last == '"') || (first == '\'' && last == '\'') || (first == '`' && last == '`') {
			value = strings.TrimSpace(value[1 : len(value)-1])
			continue
		}
		break
	}
	return value
}

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(normalizeWrappedString(MustGetString("secure_path", "")), "/"); securePath != "" {
		return securePath
	}
	if frontendPath := strings.Trim(normalizeWrappedString(MustGetString("frontend_admin_path", "")), "/"); frontendPath != "" {
		return frontendPath
	}
	return "admin"
}

func GetSubscribePath() string {
	if subscribePath := strings.Trim(normalizeWrappedString(MustGetString("subscribe_path", "")), "/"); subscribePath != "" {
		return subscribePath
	}
	return "s"
}

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