package com.lingniu.ingest.session.config;

import com.lingniu.ingest.session.CommandDispatcher;
import com.lingniu.ingest.session.NoopCommandDispatcher;
import com.lingniu.ingest.session.RedisSessionStore;
import com.lingniu.ingest.session.SessionProperties;
import com.lingniu.ingest.session.SessionStore;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;

@AutoConfiguration
@EnableConfigurationProperties(SessionProperties.class)
public class SessionCoreAutoConfiguration {

    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    @ConditionalOnProperty(prefix = "lingniu.ingest.session", name = "store", havingValue = "redis",
            matchIfMissing = true)
    @ConditionalOnMissingBean
    public SessionStore redisSessionStore(StringRedisTemplate redis, SessionProperties properties) {
        // Redis 只保存会话元数据索引；真实 Netty Channel 仍在各协议进程本地内存中。
        return new RedisSessionStore(redis, properties.getTtl());
    }

    @Bean
    @ConditionalOnMissingBean
    public CommandDispatcher commandDispatcher() {
        // 没有协议模块提供真实下行实现时使用 Noop，避免仅接收/查询部署因为缺 Bean 启动失败。
        return new NoopCommandDispatcher();
    }
}
