package com.atlassian.bitbucket.mesh.transaction;

import com.atlassian.bitbucket.mesh.rpc.util.ByteStringUtils;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcSetDefaultBranchRequest;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTransaction;
import com.google.protobuf.ByteString;

import java.util.Objects;

public class TransactSetDefaultBranchTest extends AbstractPreparedActionWriteTest {

    @Override
    protected RpcTransaction.Builder createTransaction(RpcTransaction.Builder builder) {
        return builder.setSetDefaultBranch(RpcSetDefaultBranchRequest.newBuilder()
                .setBranchId(ByteString.copyFromUtf8("refs/heads/basic_branching"))
                .setRepository(repository.getId()));
    }

    @Override
    protected RpcTransaction.Builder createTransactionThatTriggersError(RpcTransaction.Builder builder) {
        return builder.setSetDefaultBranch(RpcSetDefaultBranchRequest.newBuilder()
                .setBranchId(ByteString.copyFromUtf8("refs/heads/no-such-branch"))
                .setRepository(repository.getId()));
    }

    @Override
    protected boolean isApplied(RpcTransaction transaction) {
        String expectedBranchId = ByteStringUtils.emptyToNull(transaction.getSetDefaultBranch().getBranchId());
        return Objects.equals(expectedBranchId, agent.getHead(repository));
    }
}
