package com.bonus.canteen.core.common.threadPool;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncConfig {

   // 核心线程数和最大线程数的倍数
   private static final int THREAD_POOL_SIZE_MULTIPLIER = 2;

   // 线程池队列容量
   @Value("${async.threadPool.queueCapacity:1000}")
   private int queueCapacity;

   // 线程池线程存活时间（秒）
   @Value("${async.threadPool.keepAliveSeconds:60}")
   private int keepAliveSeconds;

   // 线程池关闭时等待任务完成的时间（秒）
   @Value("${async.threadPool.awaitTerminationSeconds:60}")
   private int awaitTerminationSeconds;

   @Bean("smartCanteenTaskExecutor")
   public AsyncTaskExecutor taskExecutor() {
      int corePoolSize = Runtime.getRuntime().availableProcessors() * THREAD_POOL_SIZE_MULTIPLIER;
       ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
      taskExecutor.setCorePoolSize(corePoolSize);
      taskExecutor.setMaxPoolSize(corePoolSize);
      taskExecutor.setThreadNamePrefix("smart-canteen-async-pool");
      taskExecutor.setQueueCapacity(queueCapacity);
      taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
      taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
      taskExecutor.setAwaitTerminationSeconds(awaitTerminationSeconds);
      taskExecutor.setTaskDecorator(new TenantTaskDecorator());
      taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
      try {
         taskExecutor.initialize();
      } catch (Exception e) {
         throw new RuntimeException("Failed to initialize ThreadPoolTaskExecutor", e);
      }

      return taskExecutor;
   }
}
