package helpers

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
	"time"
)

var secretKey = []byte("1234567890")

type TokenClaims struct {
	UserId  uint32 `json:"user_id"`
	Role    string `json:"role"`
	Expires int64  `json:"expires"`
	jwt.RegisteredClaims
}

func CreateToken(userId uint32, role string, expires time.Time) (string, error) {
	claims := TokenClaims{
		UserId:  userId,
		Role:    role,
		Expires: expires.Unix(),
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expires),
			Issuer:    "https://madsky.ru",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(secretKey)
	if err != nil {
		return "", err
	}

	return ss, nil
}

func VerifyToken(tokenString string) (*TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
		return secretKey, nil
	})

	if err != nil {
		return nil, err
	} else if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, errors.New("unknown claims type, cannot proceed")
	}

}

func CreateHashString(password string) (string, error) {
	cost := bcrypt.DefaultCost
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
	return string(bytes), err
}

func VerifyHashString(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}
