package com.atlassian.stash.internal.rest.exception;

import com.atlassian.bitbucket.rest.RestErrorMessage;
import com.atlassian.bitbucket.rest.RestErrors;
import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.bitbucket.validation.FormValidationException;
import com.atlassian.bitbucket.validation.FormErrors;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.Collection;
import java.util.Map;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;

/**
 * Maps {@link FormValidationException}s to a REST response with status code 400 (bad request).
 */
class ValidationExceptionMapper implements ExceptionMapper<FormValidationException> {

    @Override
    public Response toResponse(FormValidationException exception) {
        RestErrors.Builder errors = new RestErrors.Builder();
        FormErrors formErrors = exception.getErrors();
        for (String error : formErrors.getFormErrors()) {
            errors.add(new RestErrorMessage(error));
        }
        for (Map.Entry<String, Collection<String>> field : formErrors.getFieldErrors().entrySet()) {
            for (String message : field.getValue()) {
                errors.add(new RestErrorMessage(field.getKey(), message));
            }
        }

        return ResponseFactory.status(BAD_REQUEST)
                .entity(errors.build())
                .type(RestUtils.APPLICATION_JSON_UTF8)
                .build();
    }
}
