package space.nstart.pcp.routepassportconsumer.controller

import org.junit.jupiter.api.Test
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import space.nstart.pcp.routepassportconsumer.config.KafkaTopicsProperties
import java.nio.charset.StandardCharsets

class RouteProcessingTestControllerTest {
    @Suppress("UNCHECKED_CAST")
    private val kafkaTemplate = mock(KafkaTemplate::class.java) as KafkaTemplate<String, String>
    private val kafkaTopicsProperties = KafkaTopicsProperties(
        input = "pcp.request.survey-georeference.v1",
        processedRoute = "pcp.route.in.v1",
        routeGeoreference = "pcp.route.georeference.v1",
    )

    private val mockMvc: MockMvc = MockMvcBuilders
        .standaloneSetup(RouteProcessingTestController(kafkaTemplate, kafkaTopicsProperties))
        .build()

    @Test
    fun `GET test endpoint returns service status`() {
        mockMvc.get("/api/route-processing/test")
            .andExpect {
                status { isOk() }
                jsonPath("$.status") { value("ok") }
                jsonPath("$.service") { value("pcp-route-processing-service") }
            }
    }

    @Test
    fun `POST send endpoint publishes test passport message to input topic`() {
        mockMvc.post("/api/route-processing/test/send-passport-message")
            .andExpect {
                status { isOk() }
                jsonPath("$.status") { value("sent") }
                jsonPath("$.topic") { value("pcp.request.survey-georeference.v1") }
                jsonPath("$.resource") { value("classpath:test-passport-message.json") }
            }

        val payloadCaptor = ArgumentCaptor.forClass(String::class.java)
        verify(kafkaTemplate, times(1)).send(
            org.mockito.Mockito.eq("pcp.request.survey-georeference.v1"),
            payloadCaptor.capture(),
        )

        val expectedPayload = this::class.java.classLoader
            .getResourceAsStream("test-passport-message.json")
            ?.readAllBytes()
            ?.toString(StandardCharsets.UTF_8)
            ?: error("Не найден файл test-passport-message.json в test resources")

        kotlin.test.assertEquals(expectedPayload, payloadCaptor.value)
    }
}
