package incheon.ags.dss;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer; // 인터페이스 구현
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer { // AsyncConfigurer 구현

    @Bean(name = "dssBatchExecutor")
    public Executor getBatchAsyncExecutor() { // 메서드명 변경 (Override)
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Batch-Async-");
        executor.initialize();
        return executor;
    }

    @Override
    @Bean(name = "dssAnalysisExecutor")
    public Executor getAsyncExecutor() { // 메서드명 변경 (Override)
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Analysis-Async-");
        executor.initialize();
        return executor;
    }

    // [추가] 비동기 처리 중 발생한 예외를 로그로 출력
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.error("============ @Async Exception Occurred ============");
            log.error("Method: {}", method.getName());
            log.error("Exception: {}", ex.getMessage(), ex);
            for (Object param : params) {
                log.error("Parameter value: {}", param);
            }
            log.error("===================================================");
        };
    }
}