package dp.kotul.starter.util

import feign.FeignException
import org.slf4j.LoggerFactory
import org.springframework.boot.configurationprocessor.json.JSONObject
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.context.request.WebRequest

object ExceptionHandlerUtil {

    private val log = LoggerFactory.getLogger(ExceptionHandlerUtil::class.java)

    fun handleFeignException(
            ex: Exception,
            request: WebRequest,
            httpStatuses: List<HttpStatus> = listOf(HttpStatus.FORBIDDEN, HttpStatus.UNAUTHORIZED)
    ): ResponseEntity<Any> {
        val feignException = ex as FeignException

        if (httpStatuses.all { feignException.status() != it.value() }) {
            throw feignException
        }

        log.warn("FeignException: ", feignException)

        var message = ex.cause?.localizedMessage ?: ex.localizedMessage

        if (!feignException.contentUTF8().isNullOrBlank()) {
            val exceptionValues = JSONObject(feignException.contentUTF8())
            message = exceptionValues["message"]?.toString() ?: message
        }

        return ApiError(HttpStatus.valueOf(feignException.status()), message, request).responseEntity()
    }
}
