package space.nstart.pcp.pcp_stations_service.service

import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import space.nstart.pcp.pcp_stations_service.integration.NsiStationsResponseException

class GlobalExceptionHandle {
    @ExceptionHandler(StationsDataUnavailableException::class)
    fun handleStationsDataUnavailable(
        ex: StationsDataUnavailableException
    ): ResponseEntity<Map<String, String>> =
        ResponseEntity
            .status(HttpStatus.SERVICE_UNAVAILABLE)
            .header(
                HttpHeaders.RETRY_AFTER,
                ex.retryAfterSeconds.toString()
            )
            .body(
                mapOf(
                    "error" to "data_unavailable",
                    "message" to (
                            ex.message
                                ?: "Stations are temporarily unavailable"
                            )
                )
            )

    @ExceptionHandler(NsiStationsResponseException::class)
    fun handleNsiStationsResponseException(
        ex: NsiStationsResponseException
    ): ResponseEntity<Map<String, String>> =
        ResponseEntity
            .status(HttpStatus.BAD_GATEWAY)
            .body(
                mapOf(
                    "error" to "upstream_response_error",
                    "message" to "НСИ вернула неожиданный HTTP-статус ${ex.statusCode}"
                )
            )

}