package space.nstart.pcp.complan.service

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.RestClient
import org.springframework.web.util.UriComponentsBuilder
import space.nstart.pcp.complan.types.RequestItemDTO
import java.time.LocalDateTime
import java.util.UUID

/** Получение заявок из pcp-request-service /v1 API. */
@Service
class RequestServiceClient {
    @Value("\${complex-plan.request-service-url}")
    private lateinit var requestServiceUrl: String

    @Value("\${complex-plan.request-selection-path:/v1/requests}")
    private lateinit var requestSelectionPath: String

    fun getRequest(requestId: UUID): RequestItemDTO? =
        try {
            RestClient.create()
                .get()
                .uri(
                    UriComponentsBuilder
                        .fromUriString(requestServiceUrl)
                        .path(requestSelectionPath)
                        .path("/{requestId}")
                        .buildAndExpand(requestId)
                        .toUriString()
                )
                .retrieve()
                .body(RequestResponseDto::class.java)
                ?.toRequestItemDto()
        } catch (_: HttpClientErrorException.NotFound) {
            null
        }

    private fun RequestResponseDto.toRequestItemDto(): RequestItemDTO =
        RequestItemDTO(
            id = id,
            name = name,
            geometry = geometry,
            // pcp-request-service шлёт naive LocalDateTime без зоны — берём как есть (настенные часы UTC).
            intervalBegin = beginDateTime,
            intervalEnd = endDateTime,
            resolution = resolution(),
            importance = importance,
        )

    private fun RequestResponseDto.resolution(): Double =
        optics?.resolution
            ?: rsa?.resolution
            ?: throw IllegalStateException("Request $id has no survey resolution")
}

@JsonIgnoreProperties(ignoreUnknown = true)
data class RequestResponseDto(
    val id: UUID,
    val name: String,
    val status: String = "",
    val surveyType: String = "",
    val geometry: String,
    val importance: Double,
    val beginDateTime: LocalDateTime,
    val endDateTime: LocalDateTime,
    val kpp: List<Int> = emptyList(),
    val highPriorityTransmit: Boolean = false,
    val optics: SurveyParamsDto? = null,
    val rsa: SurveyParamsDto? = null,
    val coverage: CoverageStateDto = CoverageStateDto(),
    val createdAt: LocalDateTime? = null,
    val updatedAt: LocalDateTime? = null,
    val deletedAt: LocalDateTime? = null,
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class SurveyParamsDto(
    val resolution: Double,
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class CoverageStateDto(
    val requiredPercent: Double? = null,
    val currentPercent: Double = 0.0,
)
