package com.atlassian.bitbucket.mesh.git.exception;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcGitError;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcNonFastForwardUpdate;
import com.google.protobuf.ByteString;

import javax.annotation.Nonnull;

import static io.grpc.Status.ABORTED;
import static java.util.Objects.requireNonNull;

/**
 * Indicates a non-forced push to a ref failed because it was not fast-forward.
 */
public class NonFastForwardUpdateException extends MergeException {

    private final String rejectedRef;

    public NonFastForwardUpdateException(@Nonnull String rejectedRef) {
        super("[" + rejectedRef + "] was updated concurrently", ABORTED);

        this.rejectedRef = requireNonNull(rejectedRef, "rejectedRef");
    }

    @Nonnull
    @Override
    public RpcGitError toError() {
        return RpcGitError.newBuilder()
                .setNonFastForwardUpdate(RpcNonFastForwardUpdate.newBuilder()
                        .setRejectedRef(ByteString.copyFromUtf8(rejectedRef)))
                .build();
    }
}
