package ru.yandex.webmaster3.viewer.http.host.verification;

import com.datastax.driver.core.utils.UUIDs;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.host.verification.UserHostVerificationInfo;
import ru.yandex.webmaster3.core.host.verification.VerificationStatus;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.user.dao.UserHostVerificationYDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserAddedHostAction;

/**
 * @author avhaliullin
 */
@Description("Отменить проверку прав")
@WriteAction
@Category("verification")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CancelVerificationProcessAction extends AbstractUserAddedHostAction<CancelVerificationProcessRequest, CancelVerificationProcessResponse> {

    private final UserHostVerificationYDao userHostVerificationYDao;

    @Override
    public CancelVerificationProcessResponse process(CancelVerificationProcessRequest request) {
        if (request.getUserAddedHost().isVerified()) {
            return new CancelVerificationProcessResponse.NoVerificationInProgressError();
        }

        UserHostVerificationInfo verificationInfo =
                userHostVerificationYDao.getLatestRecord(request.getUserId(), request.getHostId());
        if (verificationInfo == null || verificationInfo.getVerificationStatus() != VerificationStatus.IN_PROGRESS) {
            return new CancelVerificationProcessResponse.NoVerificationInProgressError();
        }

        userHostVerificationYDao.addVerificationRecord(verificationInfo.copyCancelled(UUIDs.timeBased()));
        return new CancelVerificationProcessResponse.NormalResponse();
    }
}
