package com.atlassian.bitbucket.mesh.transaction;

import com.atlassian.bitbucket.mesh.junit.LogListener;
import com.atlassian.bitbucket.mesh.repository.DefaultRepositoryManager;
import com.atlassian.bitbucket.mesh.repository.ManagedRepository;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcCreateRepositoryRequest;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTransaction;
import com.google.protobuf.ByteString;
import org.junit.Rule;

import java.util.Random;

import static org.apache.commons.lang3.StringUtils.leftPad;

public class TransactCreateRepositoryTest extends AbstractPreparedActionWriteTest {

    @Rule //Suppress expected log errors from failed repository creation
    public final LogListener logListener = new LogListener(DefaultRepositoryManager.class);

    private final Random random = new Random();

    @Override
    protected RpcTransaction.Builder createTransaction(RpcTransaction.Builder builder) {
        String repositoryId = createRepositoryId();
        return builder.setRepository(repositoryId)
                .setCreateRepository(RpcCreateRepositoryRequest.newBuilder()
                        .setDefaultBranch(ByteString.copyFromUtf8("refs/heads/main"))
                        .setRepository(repositoryId));
    }

    @Override
    protected RpcTransaction.Builder createTransactionThatTriggersError(RpcTransaction.Builder builder) {
        return builder.setRepository(repository.getId())
                .setCreateRepository(RpcCreateRepositoryRequest.newBuilder()
                        .setDefaultBranch(ByteString.copyFromUtf8("refs/heads/main"))
                        .setRepository(repository.getId()));
    }

    @Override
    protected boolean isApplied(RpcTransaction transaction) {
        return repositoryManager.findById(transaction.getRepository()) != null;
    }

    private String createRepositoryId() {
        String hierarchyId = leftPad(Long.toHexString(Math.abs(random.nextLong())), 20, '0');
        return ManagedRepository.formatId(1, hierarchyId, Integer.toString(Math.abs(random.nextInt())));
    }
}
