package service

import (
	"encoding/json"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	clientv3 "go.etcd.io/etcd/client/v3"
	"strconv"
)

var (
	PaySwitchService = &sPaySwitch{
		key: "covenant/servers/loginparams/PayConfig",
	}
)

type sPaySwitch struct {
	key string
}

func (s *sPaySwitch) GetPaySwitch(ctx *gin.Context) serializer.Response {
	var payConfig forms.PayConfig

	kv := clientv3.NewKV(config.Etcd)
	getResp, err := kv.Get(ctx, s.key)
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	if len(getResp.Kvs) == 0 {
		return serializer.Suc(payConfig)
	}

	if err = json.Unmarshal(getResp.Kvs[0].Value, &payConfig); err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	return serializer.Suc(payConfig)
}

func (s *sPaySwitch) EditPaySwitch(ctx *gin.Context, req forms.EditPaySwitchReq) serializer.Response {
	payConfig := forms.PayConfig{
		IosOpenLevel: req.IosOpenLevel,
	}

	marshal, err := json.Marshal(payConfig)
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	logrus.Warnf("sPaySwitch PayConfig:%v", string(marshal))

	kv := clientv3.NewKV(config.Etcd)
	putResp, err := kv.Put(ctx, s.key, string(marshal), clientv3.WithPrevKV())
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	logrus.Warnf("Revision:%v", putResp.Header.Revision)
	if putResp.PrevKv != nil {
		logrus.Warnf("key:%v", string(putResp.PrevKv.Key))
		logrus.Warnf("Value:%v", string(putResp.PrevKv.Value))
		logrus.Warnf("Version:%v", strconv.FormatInt(putResp.PrevKv.Version, 10))
	}

	return serializer.Suc(nil)
}
