package auth

import (
	"errors"
	"fmt"
	"time"

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

var jwtSecret = []byte("supersecret")

type Claims struct {
	UserID string   `json:"userId"`
	Email  string   `json:"email"`
	Role   []string `json:"role"`
	jwt.RegisteredClaims
}

func CreateJWT(userID string, email string, role []string, duration time.Duration) (string, error) {
	claims := jwt.MapClaims{
		"userId": userID,
		"email":  email,
		"role":   role,
		"exp":    time.Now().Add(duration).Unix(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret)
}

func ParseJWT(tokenString string) (*Claims, error) {

	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		// Algorithmus Check (Sicherheit)
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unerwartete Signing-Methode: %v", token.Header["alg"])
		}
		return jwtSecret, nil
	})

	// C. Validierung
	if err != nil || !token.Valid {

		return nil, errors.New("invalid token")
	}

	return claims, nil
}
