package camel_oil

import (
	"context"
	"encoding/json"

	"github.com/gogf/gf/v2/frame/g"

	"kami/api/camel_oil/v1"
	"kami/utility/cache"
)

// UpdateSettings 更新骆驼模块设置
func (s *sCamelOil) UpdateSettings(ctx context.Context, req *v1.UpdateSettingsReq) (res *v1.UpdateSettingsRes, err error) {
	// 将设置序列化为JSON
	settingsJSON, err := json.Marshal(req.CamelOilSettings)
	if err != nil {
		return nil, err
	}

	// 保存到Redis，永不过期（设置0表示永不过期）
	settingsKey := cache.CamelOilSettings.Key("default")
	c := cache.NewCache()
	err = c.Set(ctx, settingsKey, string(settingsJSON), 0)
	if err != nil {
		return nil, err
	}

	g.Log().Info(ctx, "骆驼模块设置已更新", string(settingsJSON))

	res = &v1.UpdateSettingsRes{}
	return res, nil
}

// GetCamelOilSettings 获取骆驼模块设置的辅助函数
func (s *sCamelOil) GetCamelOilSettings(ctx context.Context) (*v1.CamelOilSettings, error) {
	settingsKey := cache.CamelOilSettings.Key("default")
	c := cache.NewCache()

	settingsData, err := c.Get(ctx, settingsKey)
	if err != nil {
		return nil, err
	}

	// 默认设置
	settings := &v1.CamelOilSettings{
		UseHaozhuPlatform:           false, // 默认不使用豪猪平台拉取手机号
		HaozhuUsername:              "",    // 默认豪猪用户名为空
		HaozhuPassword:              "",    // 默认豪猪密码为空
		LoginAccountCount:           10,    // 默认10个账号
		PrefetchConcurrencyAccounts: 10,    // 默认10个并发
		SingleAccountConcurrency:    3,     // 默认3个并发
		TargetDenominations:         []v1.DenominationSetting{},
	}

	if settingsData != nil && !settingsData.IsNil() {
		err = json.Unmarshal([]byte(settingsData.String()), settings)
		if err != nil {
			g.Log().Error(ctx, "解析骆驼模块设置失败", err)
			// 解析失败则使用默认值
		}
	}

	return settings, nil
}
