package middleware

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

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

func JWTMiddleware(c *gin.Context) {
	tokenString := c.GetHeader("Authorization")
	log.Debugln(tokenString)
	if tokenString == "" || len(tokenString) < 7 {
		c.JSON(200, apiModel.KVResponse{Success: false})
		c.Abort()
		return
	}

	ok, expired, uid, platform, platformId := util.ParseJWT(tokenString[7:])
	if !ok {
		c.JSON(200, apiModel.KVResponse{Success: false})
		c.Abort()
		return
	}

	if expired {
		c.JSON(200, apiModel.KVResponse{Success: false})
		c.Abort()
		return
	}

	log.WithField("uid", uid).Debug("jwt uid")
	c.Set("jwt-uid", uid)
	c.Set("jwt-platform", platform)
	c.Set("jwt-platform-id", platformId)
	c.Next()
}
