package server

import (
	apiModel "kv_api/model/api"
	dbModel "kv_api/model/db"
	"kv_api/util"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

func get(c *gin.Context) {
	// 获取请求参数

	k := c.Query("key")
	if k == "" {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	if len(k) > 255 {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}
	uid := c.GetString("jwt-uid")

	val, err := d.GetValue(uid, k)
	if err != nil {
		log.WithError(err).Error("get value error")
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	c.JSON(200, apiModel.KVResponse{Value: util.MustAesDecrypt(val), Success: true})
}

func set(c *gin.Context) {
	req := &apiModel.UpdateKVRequest{}
	if err := c.ShouldBindJSON(req); err != nil {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	if len(req.Key) > 255 || len(req.Value) > 255 {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	uid := c.GetString("jwt-uid")
	platform := c.GetString("jwt-platform")
	platformId := c.GetString("jwt-platform-id")

	kv := &dbModel.KVStorage{
		Uid:        uid,
		Key:        req.Key,
		Value:      util.MustAesEncrypt(req.Value),
		Platform:   platform,
		PlatformId: platformId,
	}
	err := d.SetValue(kv)
	if err != nil {
		log.WithError(err).Error("set value error")
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}
	c.JSON(200, apiModel.KVResponse{Value: req.Value, Success: true})
}

func del(c *gin.Context) {
	req := &apiModel.UpdateKVRequest{}
	if err := c.ShouldBindJSON(req); err != nil {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	if len(req.Key) > 255 || len(req.Value) > 255 {
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}

	uid := c.GetString("jwt-uid")
	platform := c.GetString("jwt-platform")
	platformId := c.GetString("jwt-platform-id")

	kv := &dbModel.KVStorage{
		Uid:        uid,
		Key:        req.Key,
		Value:      "",
		Platform:   platform,
		PlatformId: platformId,
	}
	err := d.SetValue(kv)
	if err != nil {
		log.WithError(err).Error("set value error")
		c.JSON(200, apiModel.KVResponse{Value: ""})
		return
	}
	c.JSON(200, apiModel.KVResponse{Value: req.Value, Success: true})
}
