package config

import (
	"gadmin/internal/gorm/model"

	"github.com/spf13/cast"
)

func GetInt64(key string) int64 {
	val := Get(key)
	if val == nil {
		return 0
	}
	return cast.ToInt64(val)
}

// Get 获取指定配置
func Get(key string) interface{} {
	var models *model.Config
	DB.Select("id", "value").Where("`key` = ?", key).First(&models)
	if models == nil {
		return nil
	}
	return models.Value
}

func FirstOrCreate(key string, groupName string) int64 {
	var models *model.Config
	DB.Select("id", "value").Where("`key` = ?", key).First(&models)
	if models == nil || models.ID == 0 {
		ni := model.Config{Key: key, Value: "0", DefaultValue: "0", Type: "int", Group_: groupName, Sort: 0}
		DB.Create(&ni)
		return 0
	}

	return cast.ToInt64(models.Value)
}

// Save 更新指定配置值
func Save(key string, value interface{}) {
	DB.Model(&model.Config{}).Where("`key` = ?", key).Update("value", value)
}
