package com.atlassian.bitbucket.mesh.repository;

import com.atlassian.bitbucket.mesh.AbstractStatusException;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcError;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcErrorUtils;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcForkHierarchyTooDeep;
import io.grpc.Metadata;
import io.grpc.Status;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static java.util.Objects.requireNonNull;

public class ForkHierarchyTooDeepException extends AbstractStatusException {

    private final int forkDepth;
    private final String id;

    public ForkHierarchyTooDeepException(@Nonnull String id, int forkDepth, @Nullable String message) {
        super(message, Status.FAILED_PRECONDITION);

        this.forkDepth = forkDepth;
        this.id = requireNonNull(id, "id");
    }

    public int getForkDepth() {
        return forkDepth;
    }

    @Nonnull
    public String getId() {
        return id;
    }

    @Override
    protected Metadata getTrailers() {
        return RpcErrorUtils.toMetadata(RpcError.newBuilder()
                .setForkHierarchyTooDeep(RpcForkHierarchyTooDeep.newBuilder()
                        .setRepository(id)
                        .setForkDepth(forkDepth))
                .build());
    }
}
