package com.lingniu.ingest.vehiclestate;

import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

class VehicleStateControllerTest {

    @Test
    void returnsLatestStateJson() throws Exception {
        VehicleStateRepository repository = mock(VehicleStateRepository.class);
        when(repository.getState("VIN001")).thenReturn(java.util.Optional.of("{\"speed_kmh\":\"80.5\"}"));
        MockMvc mvc = standaloneSetup(new VehicleStateController(repository)).build();

        mvc.perform(get("/api/vehicle-state/VIN001"))
                .andExpect(status().isOk())
                .andExpect(content().json("{\"speed_kmh\":\"80.5\"}"));
    }

    @Test
    void returnsLocationSafetyAndLastEventJson() throws Exception {
        VehicleStateRepository repository = mock(VehicleStateRepository.class);
        when(repository.getLocation("VIN001")).thenReturn(java.util.Optional.of("{\"longitude\":\"113.12\"}"));
        when(repository.getSafety("VIN001")).thenReturn(java.util.Optional.of("{\"hydrogen_leak_detected\":\"true\"}"));
        when(repository.getLastEvent("VIN001")).thenReturn(java.util.Optional.of("{\"eventId\":\"event-1\"}"));
        MockMvc mvc = standaloneSetup(new VehicleStateController(repository)).build();

        mvc.perform(get("/api/vehicle-state/VIN001/location"))
                .andExpect(status().isOk())
                .andExpect(content().json("{\"longitude\":\"113.12\"}"));
        mvc.perform(get("/api/vehicle-state/VIN001/safety"))
                .andExpect(status().isOk())
                .andExpect(content().json("{\"hydrogen_leak_detected\":\"true\"}"));
        mvc.perform(get("/api/vehicle-state/VIN001/last-event"))
                .andExpect(status().isOk())
                .andExpect(content().json("{\"eventId\":\"event-1\"}"));
    }

    @Test
    void returnsNotFoundWhenStateIsMissing() throws Exception {
        VehicleStateRepository repository = mock(VehicleStateRepository.class);
        when(repository.getState("VIN001")).thenReturn(java.util.Optional.empty());
        MockMvc mvc = standaloneSetup(new VehicleStateController(repository)).build();

        mvc.perform(get("/api/vehicle-state/VIN001"))
                .andExpect(status().isNotFound());
    }
}
