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.RpcDeleteRepositoryRequest;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTransaction;
import org.junit.Rule;

import java.util.Random;

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

public class TransactDeleteRepositoryTest extends AbstractPreparedActionWriteTest {

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

    private final Random random = new Random();

    @Override
    protected RpcTransaction.Builder createTransaction(RpcTransaction.Builder builder) {
        return builder.setDeleteRepository(RpcDeleteRepositoryRequest.newBuilder()
                .setRepository(repository.getId()));
    }

    @Override
    protected RpcTransaction.Builder createTransactionThatTriggersError(RpcTransaction.Builder builder) {
        String repositoryId = createRepositoryId(); // generate a repo ID that does not exist
        return builder.setRepository(repositoryId)
                .setDeleteRepository(RpcDeleteRepositoryRequest.newBuilder()
                        .setRepository(repositoryId));
    }

    @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())));
    }
}
