package space.nstart.pcp.slots_service.controller

import org.junit.jupiter.api.Test
import org.mockito.Mockito.doThrow
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.springframework.http.MediaType
import org.springframework.test.util.ReflectionTestUtils
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.test.web.servlet.setup.MockMvcBuilders
import space.nstart.pcp.slots_service.configuration.CustomValidationException
import space.nstart.pcp.slots_service.configuration.GlobalExceptionHandler
import space.nstart.pcp.slots_service.service.SlotService
import java.time.LocalDateTime

class SatelliteControllerTest {

    private val slotService = mock(SlotService::class.java)
    private val controller = SatelliteController().also {
        ReflectionTestUtils.setField(it, "slotService", slotService)
    }
    private val mockMvc: MockMvc = MockMvcBuilders.standaloneSetup(controller)
        .setControllerAdvice(GlobalExceptionHandler())
        .build()

    @Test
    fun `publish initial conditions endpoint delegates to slot service`() {
        val time = LocalDateTime.of(2026, 3, 30, 10, 0)
        mockMvc.perform(
            post("/api/satellite/56756/send-ic")
                .param("time", "2026-03-30T10:00:00")
                .contentType(MediaType.APPLICATION_JSON)
        )
            .andExpect(status().isAccepted)

        verify(slotService).publishInitialConditions(56756L, time, true)
    }

    @Test
    fun `publish initial conditions endpoint returns bad request when satellite is missing`() {
        val time = LocalDateTime.of(2026, 3, 30, 10, 0)
        doThrow(CustomValidationException("КА 999 не зарегистрирован"))
            .`when`(slotService).publishInitialConditions(999L, time, true)

        mockMvc.perform(
            post("/api/satellite/999/send-ic")
                .param("time", "2026-03-30T10:00:00")
                .contentType(MediaType.APPLICATION_JSON)
        )
            .andExpect(status().isBadRequest)
            .andExpect(jsonPath("$.error").value("КА 999 не зарегистрирован"))
    }
}
