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.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.data.redis.core.StringRedisTemplate;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

class VehicleStateAutoConfigurationTest {

    private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
            .withConfiguration(AutoConfigurations.of(VehicleStateAutoConfiguration.class))
            .withBean(EnvelopeDeadLetterSink.class, () -> record -> {})
            .withBean(StringRedisTemplate.class, () -> mock(StringRedisTemplate.class));

    @Test
    void createsVehicleStateBeansWhenEnabled() {
        contextRunner
                .withPropertyValues("lingniu.ingest.vehicle-state.enabled=true")
                .run(context -> {
                    assertThat(context).hasSingleBean(VehicleStateRepository.class);
                    assertThat(context).hasSingleBean(RedisVehicleStateRepository.class);
                    assertThat(context).hasSingleBean(VehicleStateUpdater.class);
                    assertThat(context).hasSingleBean(VehicleStateEnvelopeIngestor.class);
                    assertThat(context).hasSingleBean(EnvelopeConsumerProcessor.class);
                    assertThat(context).hasSingleBean(VehicleStateController.class);
                });
    }

    @Test
    void backsOffWhenDisabled() {
        contextRunner.run(context -> {
            assertThat(context).doesNotHaveBean(VehicleStateRepository.class);
            assertThat(context).doesNotHaveBean(VehicleStateUpdater.class);
            assertThat(context).doesNotHaveBean(VehicleStateEnvelopeIngestor.class);
            assertThat(context).doesNotHaveBean(VehicleStateController.class);
        });
    }

    @Test
    void doesNotCreateRepositoryWithoutRedisTemplate() {
        new ApplicationContextRunner()
                .withConfiguration(AutoConfigurations.of(VehicleStateAutoConfiguration.class))
                .withPropertyValues("lingniu.ingest.vehicle-state.enabled=true")
                .run(context -> assertThat(context).doesNotHaveBean(VehicleStateRepository.class));
    }
}
