package com.gameplatform.server.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;

/**
 * 异步任务配置
 * 用于设备检测等后台任务的异步处理
 */
@Configuration
@EnableAsync
public class AsyncConfig {
    private static final Logger log = LoggerFactory.getLogger(AsyncConfig.class);

    /**
     * 设备检测专用线程池
     * 避免阻塞HTTP请求处理线程
     * 优化配置以支持更高并发
     */
    @Bean(name = "deviceDetectionExecutor")
    public Executor deviceDetectionExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：增加以处理更多并发任务
        executor.setCorePoolSize(10);
        
        // 最大线程数：高峰时可扩展到更多
        executor.setMaxPoolSize(50);
        
        // 队列容量：增加队列以缓冲更多任务
        executor.setQueueCapacity(500);
        
        // 线程名称前缀，方便日志追踪
        executor.setThreadNamePrefix("DeviceDetect-");
        
        // 拒绝策略：使用丢弃最旧策略，避免阻塞HTTP线程
        // 注意：如果任务很重要，建议使用 AbortPolicy 并添加监控告警
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        
        // 线程空闲时间（秒）
        executor.setKeepAliveSeconds(60);
        
        // 允许核心线程超时
        executor.setAllowCoreThreadTimeOut(true);
        
        // 等待任务完成后再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 关闭等待时间（秒）
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        log.info("设备检测线程池已初始化: coreSize={}, maxSize={}, queueCapacity={}, rejectedPolicy=DiscardOldest", 
                executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity());
        
        return executor;
    }
    
    /**
     * 通用异步任务线程池
     * 用于其他异步操作
     */
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(20);
        
        // 最大线程数
        executor.setMaxPoolSize(100);
        
        // 队列容量
        executor.setQueueCapacity(1000);
        
        // 线程名称前缀
        executor.setThreadNamePrefix("AsyncTask-");
        
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        
        // 允许核心线程超时
        executor.setAllowCoreThreadTimeOut(true);
        
        // 等待任务完成后再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 关闭等待时间
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        log.info("通用异步任务线程池已初始化: coreSize={}, maxSize={}, queueCapacity={}", 
                executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity());
        
        return executor;
    }
}

