package cn.novalon.manage.sys.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.ReactiveAuditorAware;
import org.springframework.data.r2dbc.config.EnableR2dbcAuditing;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;

/**
 * R2DBC审计配置类
 * 
 * 文件定义：启用Spring Data R2DBC的审计功能，自动填充创建人、修改人等字段
 * 涉及业务：用户操作审计、数据变更追踪
 * 算法：使用ReactiveSecurityContextHolder获取当前认证用户
 * 
 * @author 张翔
 * @date 2026-04-01
 */
@Configuration
@EnableR2dbcAuditing(auditorAwareRef = "reactiveAuditorAware")
public class AuditingConfig {

    @Bean
    public ReactiveAuditorAware<String> reactiveAuditorAware() {
        return () -> ReactiveSecurityContextHolder.getContext()
                .map(securityContext -> securityContext.getAuthentication())
                .map(authentication -> {
                    Object principal = authentication.getPrincipal();
                    return principal instanceof String ? (String) principal : "system";
                })
                .defaultIfEmpty("system");
    }
}
