package dp.kotul.starter

import dp.kotul.starter.util.ApiError
import dp.kotul.starter.util.ExceptionHandlerUtil
import feign.FeignException
import io.jsonwebtoken.JwtException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

@ControllerAdvice
class ParentExceptionHandler : ResponseEntityExceptionHandler() {

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

    override fun handleExceptionInternal(ex: Exception, body: Any?, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
        log.warn("Handling Internal Exception: ", ex)
        var responseBody = body
        if (responseBody == null) {
            responseBody = ApiError(status, ex, request)
        }
        return super.handleExceptionInternal(ex, responseBody, headers, status, request)
    }

    @ExceptionHandler(JwtException::class)
    fun handleExpiredJwtException(ex: Exception, request: WebRequest): ResponseEntity<Any> {
        log.warn("JwtException: ", ex)
        return ApiError(HttpStatus.UNAUTHORIZED, ex, request).responseEntity()
    }

    @ExceptionHandler(FeignException::class)
    fun handleFeignExceptionForbidden(ex: Exception, request: WebRequest): ResponseEntity<Any> {
        return ExceptionHandlerUtil.handleFeignException(ex, request)
    }
}
