package com.devjob.config;

import com.devjob.logging.MdcTaskDecorator;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * EP37: @Async(EmailService 등) 실행 스레드 풀 설정.
 * - 기본 SimpleAsyncTaskExecutor는 매번 새 스레드를 생성해 비효율적이고 MDC도 전파되지 않는다.
 * - ThreadPoolTaskExecutor + MdcTaskDecorator로 MDC(requestId)를 비동기 작업까지 전파한다.
 */
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(50);
        executor.setThreadNamePrefix("devjob-async-");
        executor.setTaskDecorator(new MdcTaskDecorator());
        executor.initialize();
        return executor;
    }
}
