package com.atlassian.bitbucket.mesh.transaction;

import com.atlassian.bitbucket.mesh.repair.InteractiveRepairHelper;
import com.atlassian.bitbucket.mesh.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;

import static com.atlassian.bitbucket.mesh.git.GitProcessCompletionHandler.ERROR_REPOSITORY_READ_ONLY;
import static com.atlassian.bitbucket.mesh.transaction.ReferenceTransactionState.PREPARED;

public class ReadOnlyReferenceTransactionListener implements ReferenceTransactionListener {

    private static final Logger log = LoggerFactory.getLogger(ReadOnlyReferenceTransactionListener.class);

    private final InteractiveRepairHelper repairHelper;

    public ReadOnlyReferenceTransactionListener(InteractiveRepairHelper repairHelper) {
        this.repairHelper = repairHelper;
    }

    @Override
    public void onReferenceTransaction(@Nonnull ReferenceTransaction transaction) {
        Repository repository = transaction.getRepository();
        if (transaction.getState() == PREPARED && repository.isReadOnly()) {
            if (repairHelper.isRepairing(repository)) {
                log.debug("[{}] Allowing ref update for read-only repository that is being repaired", repository);
            } else {
                transaction.reject(ERROR_REPOSITORY_READ_ONLY);
                log.debug("[{}] Rejecting reference-transaction because the repository is read-only", repository);
            }
        }
    }
}
