package middleware

import (
	"github.com/golang-jwt/jwt"
	"iot_manager_service/config"
	"time"
)

const (
	Authorization = "Authorization"
	Audience      = "audience"
	Issuer        = "issuser"
)

var EmptyKeyFunc = func(t *jwt.Token) (interface{}, error) { return []byte(config.Instance().Server.TokenSign), nil }

type Claims struct {
	jwt.StandardClaims
	TenantId string `json:"tenant_id"`
	UserId   int64  `json:"user_id"`
	RoleId   int64  `json:"role_id"`
	UserName string `json:"user_name"`
	Random   string `json:"random"`
}

func GetAccessToken(userId, roleId int64, tenantId string, userName string, random string) (string, error) {
	jwtToken := Claims{StandardClaims: jwt.StandardClaims{
		Audience:  Audience,
		Issuer:    Issuer,
		ExpiresAt: time.Now().Add(2 * time.Hour).Unix(),
		NotBefore: time.Now().Unix(),
	},
		UserId:   userId,
		TenantId: tenantId,
		RoleId:   roleId,
		UserName: userName,
		Random:   random,
	}

	claims := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtToken)
	return claims.SignedString([]byte(config.Instance().Server.TokenSign))
}

func ParseAccessToken(authorization string) *Claims {
	token, err := jwt.ParseWithClaims(authorization, &Claims{}, EmptyKeyFunc)
	if err != nil {
		return nil
	}
	claims, ok := token.Claims.(*Claims)
	if !ok {
		return nil
	}
	return claims
}
