package io.github.js0ny.ilp_coursework.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.Optional;

/** Class that handles exception or failed request. Map all error requests to 400. */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /// Use a logger to save logs instead of passing them to user
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private final Map<String, String> badRequestMap =
            Map.of("status", "400", "error", "Bad Request");

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        log.warn("Malformed JSON received: {}", ex.getMessage());
        return badRequestMap;
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleIllegalArgument(IllegalArgumentException ex) {
        String errorMessage =
                Optional.ofNullable(ex.getMessage()).orElse("Invalid argument provided.");
        log.warn("Illegal argument in request: {}", errorMessage);
        return badRequestMap;
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleNullPointerException(Exception ex) {
        log.error("NullPointerException occurred. Return 400 by default.", ex);
        return badRequestMap;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleGeneralException(Exception ex) {
        log.error("Fallback exception received: {}", ex.getMessage());
        return badRequestMap;
    }
}
