package util

import (
	"time"

	"github.com/golang-jwt/jwt/v5"
)

const secret = "cxcZa005Y5zWH1wFgXvPGDL02Ey4ZCLAh2XFcfp7HhG3wTg5TbcnhuYhNvN3YLgt"

func GenerateJWT(uid, platform, platformId string) string {
	tk := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid":        uid,
		"platform":   platform,
		"platformId": platformId,
		"iat":        time.Now().Unix(),
		"exp":        time.Now().Add(7 * 24 * time.Hour).Unix(),
	})
	j, _ := tk.SignedString([]byte(secret))
	return j
}

func ParseJWT(token string) (ok, expired bool, uid, platform, platformId string) {
	claims := jwt.MapClaims{}
	tk, err := jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return
	}

	if !tk.Valid {
		return
	}

	uid = claims["uid"].(string)
	platform = claims["platform"].(string)
	platformId = claims["platformId"].(string)
	exp := claims["exp"].(float64)
	if time.Now().Unix() > int64(exp) {
		expired = true
		return
	}
	ok = true
	return

}
