package space.nstart.pcp.pcp_stations_service.configuration

import org.springframework.http.ResponseEntity
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.support.WebExchangeBindException
import reactor.core.publisher.Mono

class CustomValidationException(message: String) : RuntimeException(message)
class CustomErrorException(message: String) : RuntimeException(message)


@ControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(CustomValidationException::class)
    fun handleValidation(ex: CustomValidationException): ResponseEntity<Map<String, String>> {
        return ResponseEntity.badRequest()
            .body(mapOf("error" to ex.message!!))
    }
    @ExceptionHandler(CustomErrorException::class)
    fun handleError(ex: CustomErrorException): ResponseEntity<Map<String, String>> {
        return ResponseEntity.internalServerError()
            .body(mapOf("error" to ex.message!!))
    }
    @ExceptionHandler(WebExchangeBindException::class)
    fun handleValidationExceptions(ex: WebExchangeBindException): Mono<ResponseEntity<Map<String, String>>> {
        val errors = mutableMapOf<String, String>()
        ex.bindingResult.fieldErrors.forEach { error ->
            errors[error.field] = error.defaultMessage ?: "Validation error"
        }
        return Mono.just(ResponseEntity.badRequest().body(errors))
    }
    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleValidationExceptions(ex: MethodArgumentNotValidException): ResponseEntity<Map<String, String>> {
        val errors = mutableMapOf<String, String>()
        ex.bindingResult.allErrors.forEach { error ->
            val fieldName = (error as FieldError).field
            val errorMessage = error.defaultMessage
            errors[fieldName] = errorMessage ?: "Validation error"
        }
        return ResponseEntity.badRequest().body(errors)
    }
}