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.DeleteRepositoryParameters;
import com.atlassian.bitbucket.mesh.repository.Repository;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcCreateRepositoryRequest;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcTransaction;
import com.google.protobuf.ByteString;
import org.junit.After;
import org.junit.Rule;

public class TransactForkRepositoryTest extends AbstractPreparedActionWriteTest {

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

    @After
    public void tearDown() {
        Repository fork = repositoryManager.findById(getForkId());
        if (fork != null) {
            repositoryManager.delete(new DeleteRepositoryParameters.Builder(fork).build());
        }
    }

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

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

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

    private String getForkId() {
        //Use the same partition and hierarchy but add a suffix to generate a new ID
        return repository.getId() + "927342";
    }
}
