package com.lingniu.ingest.vehiclestate.config;

import com.lingniu.ingest.api.consumer.EnvelopeConsumerProcessor;
import com.lingniu.ingest.api.consumer.EnvelopeDeadLetterSink;
import com.lingniu.ingest.vehiclestate.RedisVehicleStateRepository;
import com.lingniu.ingest.vehiclestate.VehicleStateController;
import com.lingniu.ingest.vehiclestate.VehicleStateEnvelopeIngestor;
import com.lingniu.ingest.vehiclestate.VehicleStateRepository;
import com.lingniu.ingest.vehiclestate.VehicleStateUpdater;
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.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;

@AutoConfiguration
@ConditionalOnProperty(prefix = "lingniu.ingest.vehicle-state", name = "enabled", havingValue = "true")
public class VehicleStateAutoConfiguration {

    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    @ConditionalOnMissingBean
    public VehicleStateRepository vehicleStateRepository(StringRedisTemplate redis) {
        // 车辆状态模块依赖 Redis；没有 Redis Bean 时不自动启用，避免误以为它是历史库。
        return new RedisVehicleStateRepository(redis);
    }

    @Bean
    @ConditionalOnBean(VehicleStateRepository.class)
    @ConditionalOnMissingBean
    public VehicleStateUpdater vehicleStateUpdater(VehicleStateRepository repository) {
        return new VehicleStateUpdater(repository);
    }

    @Bean
    @ConditionalOnBean(VehicleStateUpdater.class)
    @ConditionalOnMissingBean
    public VehicleStateEnvelopeIngestor vehicleStateEnvelopeIngestor(VehicleStateUpdater updater) {
        return new VehicleStateEnvelopeIngestor(updater);
    }

    @Bean
    @ConditionalOnBean({VehicleStateEnvelopeIngestor.class, EnvelopeDeadLetterSink.class})
    @ConditionalOnMissingBean(name = "vehicleStateEnvelopeConsumerProcessor")
    public EnvelopeConsumerProcessor vehicleStateEnvelopeConsumerProcessor(VehicleStateEnvelopeIngestor ingestor,
                                                                          EnvelopeDeadLetterSink deadLetterSink) {
        // Bean 名必须和 Kafka 默认 binding 对齐，KafkaEnvelopeConsumerFactory 才能自动创建 worker。
        return new EnvelopeConsumerProcessor("vehicle-state", ingestor, deadLetterSink);
    }

    @Bean
    @ConditionalOnBean(VehicleStateRepository.class)
    @ConditionalOnMissingBean
    public VehicleStateController vehicleStateController(VehicleStateRepository repository) {
        return new VehicleStateController(repository);
    }
}
