package tool

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

type Jwt struct {
	SecreteKey string
	Claims     *Claim
}

type Claim struct {
	CustomerClaim any
	jwt.RegisteredClaims
}

func NewJwt(secrete string, ttl int64, customerClaim ...any) *Jwt {
	return &Jwt{
		SecreteKey: secrete,
		Claims: &Claim{
			customerClaim,
			jwt.RegisteredClaims{
				ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(ttl))),
			},
		},
	}
}

func (j *Jwt) Encode() (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, j.Claims)
	return token.SignedString([]byte(j.SecreteKey))
}

func (j *Jwt) Decode(tokenString string) (*jwt.Token, error) {
	token, err := jwt.ParseWithClaims(tokenString, j.Claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(j.SecreteKey), nil
	})
	if err != nil || !token.Valid {
		return nil, err
	}
	return token, nil
}
