package services

import (
	"golang.org/x/crypto/bcrypt"
	"os"
	"time"

	"github.com/golang-jwt/jwt/v5"

	"git.dynamicdiscord.de/kalipso/zineshop/models"
	"git.dynamicdiscord.de/kalipso/zineshop/repositories"
)

var (
	Users UserService = UserService{}
)

type UserService struct{}

func (u *UserService) Register(name string, email string, password string, isAdmin bool) (models.User, error) {
	//hash pw
	hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)

	if err != nil {
		return models.User{}, err
	}

	user := models.User{Name: name, Email: email, Password: string(hash), IsAdmin: isAdmin}
	_, err = repositories.Users.Create(user)

	if err != nil {
		return models.User{}, err
	}

	return user, nil
}

// return jwt tokenstring on success
func (u *UserService) Login(email string, password string) (string, error) {
	//lookup requested user
	user, err := repositories.Users.GetByEmail(email)

	if err != nil {
		return "", err
	}

	// compare sent with saved pass
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))

	if err != nil {
		return "", err
	}

	//generate jwt token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"sub": user.ID,
		"exp": time.Now().Add(time.Hour * 24).Unix(),
	})

	// Sign and get the complete encoded token as a string using the secret
	tokenString, err := token.SignedString([]byte(os.Getenv("SECRET")))

	if err != nil {
		return "", err
	}

	return tokenString, nil
}
