package cn.meowrain.aioj.backend.fileservice.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步配置类
 *
 * @author meowrain
 * @since 2026-01-10
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig {

    @Value("${file-config.async.core-pool-size:2}")
    private int corePoolSize;

    @Value("${file-config.async.max-pool-size:5}")
    private int maxPoolSize;

    @Value("${file-config.async.queue-capacity:100}")
    private int queueCapacity;

    @Value("${file-config.async.thread-name-prefix:file-async-}")
    private String threadNamePrefix;

    @Bean("fileExecutor")
    public Executor fileExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        log.info("文件异步线程池初始化完成: coreSize={}, maxSize={}, queueCapacity={}",
                corePoolSize, maxPoolSize, queueCapacity);
        return executor;
    }
}
