package manager

import (
	"Wine-Server/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
)

func PublicKeyHandler(ctx *gin.Context) {
	ctx.JSON(utils.HttpOk, utils.Success(utils.JsonType{"public": utils.ClientPub, "private": utils.ClientPri}))
}

func EncryptTestHandler(ctx *gin.Context) {
	type Param struct {
		User string `json:"user"`
		Pass string `json:"pass"`
	}
	var param Param
	err := ctx.ShouldBind(&param)
	if err != nil {
		fmt.Println(err.Error())
		ctx.JSON(utils.HttpOk, utils.Fail("param error 1"))
		return
	}

	param.Pass, err = utils.Decrypt(param.Pass)
	if err != nil {
		fmt.Println(err.Error())
		ctx.JSON(utils.HttpOk, utils.Fail("param error 3"))
		return
	}

	fmt.Printf("user: %s, password: %s\n", param.User, param.Pass)
	ctx.JSON(utils.HttpOk, utils.Success(param.Pass))
}

func RegisterHandler(ctx *gin.Context) {
	_, ok := ctx.GetPostForm("device")
	if !ok {
		ctx.JSON(utils.HttpOk, utils.Fail("param lost."))
	}
	token := utils.RandomString(16, utils.AlphaNumPatten)
	key := fmt.Sprintf("Seller-%s", token)
Diff:
	for {
		res, err := utils.Redis.Get(ctx, key).Result()
		switch {
		case err == redis.Nil:
			break Diff
		case err != nil:
			ctx.JSON(utils.HttpOk, utils.Fail("获取Token失败"))
			return
		case res == "":
			break Diff
		}
		token = utils.RandomString(16, utils.AlphaNumPatten)
		key = fmt.Sprintf("Seller-%s", token)
	}
	utils.Redis.Set(ctx, key, 1, 0)

	ctx.Header("Token", token)
	ctx.JSON(utils.HttpOk, utils.Success(token))
}
