package ru.yandex.webmaster3.viewer.http.spam;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.host.verification.VerificationType;
import ru.yandex.webmaster3.core.http.request.RequestContext;
import ru.yandex.webmaster3.core.util.HostSpamUtil;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.core.host.service.HostOwnerService;
import ru.yandex.webmaster3.storage.spam.VerificationsForOwnerYDao;
import ru.yandex.webmaster3.viewer.http.filter.AbstractSpamCaptchaFilter;
import ru.yandex.webmaster3.core.spam.ShowCaptchaReason;
import ru.yandex.webmaster3.viewer.http.host.verification.VerifyHostRequest;

import java.util.EnumSet;
import java.util.Set;

/**
 * @author avhaliullin
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class VerificationSpamCaptchaFilter extends AbstractSpamCaptchaFilter<VerifyHostRequest> {
    private static final Set<VerificationType> SUSPICIOUS_METHODS = EnumSet.of(VerificationType.HTML_FILE, VerificationType.META_TAG);
    private static final int PER_OWNER_THRESHOLD = 2;

    private final HostOwnerService hostOwnerService;
    private final VerificationsForOwnerYDao verificationsForOwnerYDao;

    @Override
    protected ShowCaptchaReason shouldShowCaptcha(RequestContext ctx, VerifyHostRequest verifyHostRequest)  {
        WebmasterHostId hostId = verifyHostRequest.getHostId();
        if (!SUSPICIOUS_METHODS.contains(verifyHostRequest.getVerificationType())) {
            return null;
        }
        if (!HostSpamUtil.isSuspiciousHost(hostId)) {
            return null;
        }
        WebmasterHostId owner = hostOwnerService.getHostOwner(hostId);
        long verifications = verificationsForOwnerYDao.countVerifications(owner);
        if (verifications >= PER_OWNER_THRESHOLD) {
            return ShowCaptchaReason.HOST_VERIFICATION_SPAM;
        }
        return null;
    }
}
