package com.atlassian.bitbucket.internal.branch.rest;

import com.atlassian.bitbucket.ForbiddenException;
import com.atlassian.bitbucket.rest.RestErrors;
import com.atlassian.bitbucket.rest.exception.UnhandledExceptionMapper;
import com.atlassian.bitbucket.rest.exception.UnhandledExceptionMapperHelper;
import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.sun.jersey.spi.resource.Singleton;

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

@Provider
@Singleton
public class BranchUtilsExceptionMapper extends UnhandledExceptionMapper {

    public BranchUtilsExceptionMapper(UnhandledExceptionMapperHelper helper) {
        super(helper);
    }

    @Override
    public Response toResponse(Exception exception) {
        if (exception instanceof ForbiddenException) {
            return ResponseFactory
                    .status(Response.Status.UNAUTHORIZED)
                    .entity(new RestErrors(exception.getLocalizedMessage()))
                    .type(RestUtils.APPLICATION_JSON_UTF8)
                    .build();
        }

        return super.toResponse(exception);
    }
}
