package com.ankurm.jpaauditing;

import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Variant of SecurityContextAuditorAware for batch jobs, schedulers and message listeners:
 * when there is no logged-in user, record a fixed "system" actor instead of leaving the
 * column NULL. Use this only if created_by is NOT NULL or you want jobs to be visible in reports.
 */
public class SystemFallbackAuditorAware implements AuditorAware<String> {

    public static final String SYSTEM = "system";

    @Override
    public Optional<String> getCurrentAuditor() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            return Optional.of(SYSTEM);
        }
        return Optional.of(auth.getName());
    }
}
