package jwt

import (
	"fmt"
	"log"
	"time"

	"com.sismedika.com.absensi/pkg/config"
	"github.com/dgrijalva/jwt-go"
)

// var conf = config.Data

// GenerateToken generates a jwt token and assign a username to it's claims and return it
func GenerateToken(M_StaffEmail string, M_StaffIDGoogleSignIn string) (string, int64, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	/* Create a map to store our claims */
	claims := token.Claims.(jwt.MapClaims)
	/* Set token claims */
	expired := time.Now().Add(time.Minute * time.Duration(config.Data.GetInt("tokenExpiration"))).Unix()
	claims["M_StaffIDGoogleSignIn"] = M_StaffIDGoogleSignIn
	claims["M_StaffEmail"] = M_StaffEmail
	claims["exp"] = expired
	tokenString, err := token.SignedString([]byte(config.Data.Get("secretkey")))
	if err != nil {
		return "", 0, fmt.Errorf("GENERATE_TOKEN_FAILED")
	}
	return tokenString, expired, nil
}

// ParseToken parses a jwt token and returns the username in it's claims
func ParseToken(tokenStr string) (string, string, error) {
	claims := jwt.MapClaims{}

	token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.Data.Get("secretkey")), nil
	})
	if err != nil {
		v, _ := err.(*jwt.ValidationError)

		if v.Errors == jwt.ValidationErrorExpired {
			log.Printf("parse token 1: %v\n", err)
			return "", "", fmt.Errorf("TOKEN_EXPIRED")
		}

		log.Printf("parse token 2: %v\n", err)
		return "", "", fmt.Errorf("TOKEN_INVALID")
	}

	if !token.Valid {
		log.Printf("token invalid: %v\n", err)
		return "", "", fmt.Errorf(("TOKEN_INVALID"))
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		if !ok {
			return "", "", fmt.Errorf(("TOKEN_INVALID"))
		}
		// type of user_id is float64: https://stackoverflow.com/questions/70705673/panic-interface-conversion-interface-is-float64-not-int64
		if claims["M_StaffIDGoogleSignIn"] == nil {
			return "", "", fmt.Errorf(("TOKEN_INVALID"))
		}
		if claims["M_StaffEmail"] == nil {
			return "", "", fmt.Errorf(("TOKEN_INVALID"))
		}
		M_StaffIDGoogleSignIn := claims["M_StaffIDGoogleSignIn"].(string)
		M_StaffEmail := claims["M_StaffEmail"].(string)
		return M_StaffIDGoogleSignIn, M_StaffEmail, nil
	} else {
		log.Printf("token claims: %v\n", err)
		return "", "", fmt.Errorf(("TOKEN_INVALID"))
	}
}
