package skilldesk.config;

import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.server.exceptions.response.Error;
import io.micronaut.http.server.exceptions.response.ErrorContext;
import io.micronaut.http.server.exceptions.response.ErrorResponseProcessor;
import jakarta.inject.Singleton;

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

@Singleton
public class SimpleErrorResponseProcessor implements ErrorResponseProcessor<Object> {

    @Override
    public MutableHttpResponse<Object> processResponse(ErrorContext errorContext, MutableHttpResponse<?> response) {
        Optional<Error> error = errorContext.getErrors().stream().findFirst();
        @SuppressWarnings("unchecked")
        MutableHttpResponse<Object> resp = (MutableHttpResponse<Object>) response;
        if (error.isPresent()) {
            resp.body(Map.of("detail", error.get().getMessage()));
        }
        return resp;
    }
}
