package com.spring.common.jpa;

import java.util.Optional;

import org.springframework.data.domain.AuditorAware;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.spring.infra.security.domain.UserPrincipal;

public class UserAuditorAware implements AuditorAware<String> {
    
    @Override
    public @NonNull Optional<String> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return Optional.empty();
        }
        return Optional.of(((UserPrincipal) authentication.getPrincipal()).getAgentUser().getUserId());
    }

}
