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

import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.atlassian.bitbucket.NoSuchEntityException;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.rest.RestErrorMessage;
import com.atlassian.bitbucket.auth.AuthenticationContext;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

/**
 * To avoid bleeding of data for anonymous users treat {@link NoSuchEntityException} as unauthorized.
 *
 * @since 2.5
 */
class NoSuchEntityExceptionMapper implements ExceptionMapper<NoSuchEntityException> {

    private final AuthenticationContext authenticationContext;
    private final I18nService i18nService;

    public NoSuchEntityExceptionMapper(AuthenticationContext authenticationContext, I18nService i18nService) {
        this.authenticationContext = authenticationContext;
        this.i18nService = i18nService;
    }

    @Override
    public Response toResponse(NoSuchEntityException exception) {
        if (!authenticationContext.isAuthenticated()) {
            return ResponseFactory.status(Response.Status.UNAUTHORIZED)
                    // TODO This needs to be the same as ExceptionRewriteAdvice
                    .entity(new RestErrorMessage(i18nService.getMessage("bitbucket.rest.service.accessdenied")))
                    .type(RestUtils.APPLICATION_JSON_UTF8)
                    .build();
        }
        // Fall through to the default handler
        return null;
    }
}
