package service

import (
	"github.com/golang-jwt/jwt/v5"
	"github.com/rs/zerolog"
	"go-humas-be/app/database/entity"
	"go-humas-be/app/module/users/repository"
	"strings"
	"time"
)

func GetUserInfo(log zerolog.Logger, repo repository.UsersRepository, bearerToken string) *entity.Users {
	tokenString := strings.TrimPrefix(bearerToken, "Bearer ")
	token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
	if err != nil {
		return nil
	}
	claims := token.Claims.(jwt.MapClaims)
	sub := claims["sub"].(string)

	user, err := repo.FindByKeycloakId(sub)
	if err != nil {
		return nil
	}

	log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:GetUserInfo", "UserInfo:GetUserInfo").
		Interface("payload", user).Msg("")

	return user
}
