package ru.yandex.webmaster3.storage.checklist.dao;

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.checklist.data.SiteProblemStorageType;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemStorageService;
import ru.yandex.webmaster3.storage.host.AllVerifiedHostsCacheService;

/**
 * ishalaru
 * 26.04.2021
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ValidateSiteProblemService {
    private final SiteProblemStorageService siteProblemStorageService;
    private final AllVerifiedHostsCacheService allVerifiedHostsCacheService;

    public boolean hostInWebmaster(WebmasterHostId hostId, SiteProblemTypeEnum problemType) {
        return hostInWebmaster(hostId, problemType.getStorageType());
    }

    // Не хотим сохранять проблемы для неподтвержденных хостов, чтобы не засорять базу
    public boolean hostInWebmaster(WebmasterHostId hostId, SiteProblemStorageType storageType) {
        if (storageType.shouldAlwaysUpdateProblem()) {
            return true;
        }

        List<WebmasterHostId> problemHosts = storageType.allPossibleHostsForProblem(siteProblemStorageService.toProblemHostId(hostId, storageType));
        var verifiedHostOpt = problemHosts.stream().filter(allVerifiedHostsCacheService::contains).findAny();
        boolean shouldUpdate = verifiedHostOpt.isPresent();
        log.info("Should update problem for {}: {}, {}", hostId, shouldUpdate, verifiedHostOpt.orElse(null));

        return shouldUpdate;
    }
}
