package com.kym.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 虚拟线程配置类
 * Java 21 Virtual Threads 统一配置
 *
 * @author skyline
 * @date 2026-01-11
 */
@Configuration
@Slf4j
public class VirtualThreadConfig {

    /**
     * 创建虚拟线程执行器用于异步任务
     * 虚拟线程非常轻量，可以创建数百万个而不会耗尽系统资源
     */
    @Bean("virtualThreadExecutor")
    public ExecutorService virtualThreadExecutor() {
        log.info("初始化虚拟线程执行器 (Virtual Thread Executor)");
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    /**
     * 创建命名的虚拟线程执行器，便于追踪和调试
     */
    @Bean("namedVirtualThreadExecutor")
    public ExecutorService namedVirtualThreadExecutor() {
        log.info("初始化命名虚拟线程执行器 (Named Virtual Thread Executor)");
        return Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
                .name("vt-", 0)
                .factory());
    }

    /**
     * 为消息处理创建专用的虚拟线程执行器
     */
    @Bean("messageVirtualThreadExecutor")
    public ExecutorService messageVirtualThreadExecutor() {
        log.info("初始化消息处理虚拟线程执行器 (Message Virtual Thread Executor)");
        return Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
                .name("vt-msg-", 0)
                .factory());
    }

    /**
     * 为调度任务创建专用的虚拟线程执行器
     */
    @Bean("schedulerVirtualThreadExecutor")
    public ExecutorService schedulerVirtualThreadExecutor() {
        log.info("初始化调度虚拟线程执行器 (Scheduler Virtual Thread Executor)");
        return Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
                .name("vt-scheduler-", 0)
                .factory());
    }
}
