package com.lingniu.ingest.vehiclestate;

import org.junit.jupiter.api.Test;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Optional;

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

class RedisVehicleStateRepositoryTest {

    @Test
    void writesAndReadsHotStateJsonByStableRedisKey() {
        StringRedisTemplate redis = mock(StringRedisTemplate.class);
        @SuppressWarnings("unchecked")
        ValueOperations<String, String> ops = mock(ValueOperations.class);
        when(redis.opsForValue()).thenReturn(ops);
        when(ops.get("vehicle:state:VIN001")).thenReturn("{\"vin\":\"VIN001\"}");

        RedisVehicleStateRepository repository = new RedisVehicleStateRepository(redis);

        repository.putState("VIN001", "{\"vin\":\"VIN001\"}");
        Optional<String> value = repository.getState("VIN001");

        verify(ops).set("vehicle:state:VIN001", "{\"vin\":\"VIN001\"}");
        assertThat(value).contains("{\"vin\":\"VIN001\"}");
    }

    @Test
    void writesLocationSafetyAndLastEventToSeparateKeys() {
        StringRedisTemplate redis = mock(StringRedisTemplate.class);
        @SuppressWarnings("unchecked")
        ValueOperations<String, String> ops = mock(ValueOperations.class);
        when(redis.opsForValue()).thenReturn(ops);

        RedisVehicleStateRepository repository = new RedisVehicleStateRepository(redis);

        repository.putLocation("VIN001", "{\"longitude\":113.12}");
        repository.putSafety("VIN001", "{\"hydrogen_leak_detected\":true}");
        repository.putLastEvent("VIN001", "{\"eventId\":\"event-1\"}");

        verify(ops).set("vehicle:location:VIN001", "{\"longitude\":113.12}");
        verify(ops).set("vehicle:safety:VIN001", "{\"hydrogen_leak_detected\":true}");
        verify(ops).set("vehicle:event:last:VIN001", "{\"eventId\":\"event-1\"}");
    }
}
