package com.lingniu.ingest.historyapp;

import com.lingniu.ingest.api.consumer.EnvelopeConsumerProcessor;
import com.lingniu.ingest.sink.kafka.KafkaEnvelopeConsumerFactory;
import com.lingniu.ingest.sink.kafka.KafkaEnvelopeConsumerRunner;
import com.lingniu.ingest.sink.kafka.KafkaEnvelopeConsumerWorker;
import com.lingniu.ingest.sink.kafka.KafkaSinkProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;
import java.util.Map;

@Configuration(proxyBeanMethods = false)
public class VehicleHistoryKafkaConsumerConfiguration {

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "lingniu.ingest.sink.kafka.consumer", name = "enabled", havingValue = "true")
    public KafkaEnvelopeConsumerRunner vehicleHistoryKafkaEnvelopeConsumerRunner(
            @Qualifier("eventHistoryEnvelopeConsumerProcessor") EnvelopeConsumerProcessor processor,
            @Qualifier("eventHistoryRawEnvelopeConsumerProcessor") EnvelopeConsumerProcessor rawProcessor,
            KafkaSinkProperties props) {
        List<KafkaEnvelopeConsumerWorker> workers = new KafkaEnvelopeConsumerFactory().createWorkers(
                Map.of(
                        "eventHistoryGb32960EnvelopeConsumerProcessor", processor,
                        "eventHistoryJt808EnvelopeConsumerProcessor", processor,
                        "eventHistoryYutongMqttEnvelopeConsumerProcessor", processor,
                        "eventHistoryGb32960RawEnvelopeConsumerProcessor", rawProcessor,
                        "eventHistoryJt808RawEnvelopeConsumerProcessor", rawProcessor,
                        "eventHistoryYutongMqttRawEnvelopeConsumerProcessor", rawProcessor),
                props);
        if (workers.isEmpty()) {
            throw new IllegalStateException("no vehicle history kafka consumer workers created; check consumer bindings");
        }
        return new KafkaEnvelopeConsumerRunner(
                workers,
                Duration.ofMillis(props.getConsumer().getPollTimeoutMillis()),
                Duration.ofMillis(props.getConsumer().getLoopBackoffMillis()),
                props.getConsumer().isAutoStartup());
    }
}
