package com.vaessl.app.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;

import static com.vaessl.app.exception.ErrorMessage.*;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail handleEmptyCredentialInput(MethodArgumentNotValidException e) {

        String defaultMessages = e.getBindingResult().getFieldErrors().stream()
                .map(field -> field.getDefaultMessage()).collect(Collectors.joining(", "));

        return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(),
                BAD_REQUEST_EMPTY_FIELDS.getMessage() + " [" + defaultMessages + "]");
    }

    @ExceptionHandler(HttpClientErrorException.Unauthorized.class)
    public ProblemDetail handleUnauthorizedAccess(HttpClientErrorException e) {

        return ProblemDetail.forStatusAndDetail(UNAUTHORIZED_WRONG_LOGIN.getStatus(),
                UNAUTHORIZED_WRONG_LOGIN.getMessage());
    }

    // Catches any other 4xx from a remote API (e.g. 404 caused by a changed endpoint).
    // Must come after the Unauthorized handler so Spring matches 401 there first.
    @ExceptionHandler(HttpClientErrorException.class)
    public ProblemDetail handleRemoteClientError(HttpClientErrorException e) {
        log.error("Remote API returned {}: {}", e.getStatusCode(), e.getResponseBodyAsString());
        return ProblemDetail.forStatusAndDetail(REMOTE_API_CLIENT_ERROR.getStatus(),
                REMOTE_API_CLIENT_ERROR.getMessage() + e.getStatusCode());
    }

    @ExceptionHandler(ResourceAccessException.class)
    public ProblemDetail handleNoConnection(ResourceAccessException e) {

        return ProblemDetail.forStatusAndDetail(SERVICE_UNAVAILABLE_UNREACHABLE_URL.getStatus(),
                SERVICE_UNAVAILABLE_UNREACHABLE_URL.getMessage());
    }

    @ExceptionHandler(HttpServerErrorException.class)
    public ProblemDetail handleTimeoutOrNotFound(HttpServerErrorException e) {
        log.error("Remote API server error {}: {}", e.getStatusCode(), e.getResponseBodyAsString());
        return ProblemDetail.forStatusAndDetail(e.getStatusCode(),
                SERVER_ERROR_GENERAL.getMessage() + e.getStatusText());
    }

    @ExceptionHandler(WrongServiceTypeException.class)
    public ProblemDetail handleWrongServiceType(WrongServiceTypeException e) {
        return ProblemDetail.forStatusAndDetail(WRONG_SERVICE_TYPE.getStatus(),
                WRONG_SERVICE_TYPE.getMessage());
    }

    @ExceptionHandler(EmptyCredentialsException.class)
    public ProblemDetail handleEmptyCredentials(EmptyCredentialsException e) {
        return ProblemDetail.forStatusAndDetail(BAD_REQUEST_EMPTY_FIELDS.getStatus(),
                BAD_REQUEST_EMPTY_FIELDS.getMessage() + " " + e.getMissingFields());
    }

    @ExceptionHandler(ConnectionNotFoundException.class)
    public ProblemDetail handleConnectionNotFound(ConnectionNotFoundException e) {
        return ProblemDetail.forStatusAndDetail(CONNECTION_NOT_FOUND.getStatus(),
                CONNECTION_NOT_FOUND.getMessage());
    }

    @ExceptionHandler(RemoteApiException.class)
    public ProblemDetail handleRemoteApiException(RemoteApiException e) {
        log.error("Remote API empty body: {}{}", e.getAppUrl(), e.getPath());
        return ProblemDetail.forStatusAndDetail(REMOTE_API_EMPTY_RESPONSE.getStatus(),
                REMOTE_API_EMPTY_RESPONSE.getMessage() + e.getAppUrl() + e.getPath());
    }
}
