package auth

import (
	"time"

	"git.gocasts.ir/ebhomengo/niki/entity"
	"github.com/golang-jwt/jwt/v4"
)

func (s Service) CreateAccessToken(user entity.Authenticable) (string, error) {
	return s.createToken(user.ID, user.Role, s.Config.AccessSubject, s.Config.AccessExpirationTime)
}

func (s Service) CreateRefreshToken(user entity.Authenticable) (string, error) {
	return s.createToken(user.ID, user.Role, s.Config.RefreshSubject, s.Config.RefreshExpirationTime)
}

func (s Service) createToken(userID uint, role, subject string, expireDuration time.Duration) (string, error) {
	// create a signer for rsa 256
	// TODO - replace with rsa 256 RS256 - https://github.com/golang-jwt/jwt/blob/main/http_example_test.go

	// set our claims
	claims := Claims{
		RegisteredClaims: jwt.RegisteredClaims{
			Subject:   subject,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
		},
		UserID: userID,
		Role:   role,
	}

	// TODO - add sign method to config
	accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := accessToken.SignedString([]byte(s.Config.SignKey))
	if err != nil {
		return "", err
	}

	return tokenString, nil
}
