package service

import (
	"fmt"
	"strconv"
	"time"

	baseCnf "git.ego.freeddns.org/egommerce/go-api-pkg/config"
	"github.com/golang-jwt/jwt"
)

var (
	tokenExpireTime int
	tokenSecret     []byte
)

func init() {
	tokenExpireTime, _ = strconv.Atoi(baseCnf.GetEnv("JWT_TOKEN_EXPIRE_TIME", "5"))
	tokenSecret = []byte(baseCnf.GetEnv("JWT_SECRET_KEY", "B413IlIv9nKQfsMCXTE0Cteo4yHgUEfqaLfjg73sNlh")) // FIXME env: JWT_SECRET_KEY !!!

	JWTService = &JWT{tokenExpireTime, tokenSecret}
}

type JWT struct {
	tokenExpireTime int
	tokenSecret     []byte
}

func (s *JWT) CreateToken() (string, error) {
	claims := &jwt.StandardClaims{
		ExpiresAt: time.Now().Add(time.Duration(s.tokenExpireTime) * time.Minute).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(s.tokenSecret)
}

func (s *JWT) ValidateToken(tokenStr string) error {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		return s.tokenSecret, nil
	})

	if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return nil
	}

	return err
}
