package tech.easyflow.ai.documentimport.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

/**
 * 文档导入状态 Redis 广播配置。
 */
@Configuration
public class DocumentImportStatusBroadcastConfig {

    private static final Logger LOG = LoggerFactory.getLogger(DocumentImportStatusBroadcastConfig.class);

    /**
     * 创建文档导入状态广播监听容器。
     *
     * @param connectionFactory Redis 连接工厂
     * @param streamService 文档导入状态流服务
     * @param properties 文档导入监控配置
     * @return Redis 消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer documentImportStatusListenerContainer(
        RedisConnectionFactory connectionFactory,
        DocumentImportTaskStatusStreamService streamService,
        DocumentImportStatusBroadcastProperties properties
    ) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(
            new DocumentImportStatusMessageListener(streamService),
            new ChannelTopic(properties.getStatusBroadcastChannel())
        );
        return container;
    }

    /**
     * 文档导入状态广播监听器。
     */
    private static final class DocumentImportStatusMessageListener implements MessageListener {

        private final DocumentImportTaskStatusStreamService streamService;

        /**
         * 创建监听器。
         *
         * @param streamService 文档导入状态流服务
         */
        private DocumentImportStatusMessageListener(DocumentImportTaskStatusStreamService streamService) {
            this.streamService = streamService;
        }

        /**
         * 处理 Redis 广播消息。
         *
         * @param message 消息
         * @param pattern 订阅模式
         */
        @Override
        public void onMessage(Message message, byte[] pattern) {
            String payload = new String(message.getBody(), StandardCharsets.UTF_8);
            try {
                streamService.publishLocal(new BigInteger(payload));
            } catch (RuntimeException e) {
                LOG.warn("处理文档导入状态广播失败: payload={}", payload, e);
            }
        }
    }
}
