package ru.yandex.webmaster3.viewer.http.searchquery.recommended;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.host.service.MirrorService2;
import ru.yandex.webmaster3.storage.recommendedquery.RecommendedQueriesService;
import ru.yandex.webmaster3.storage.recommendedquery.dao.DomainsWithDirectDynamicAdsYDao;
import ru.yandex.webmaster3.storage.recommendedquery.dao.RecommendedQueriesCHDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;

/**
 * @author avhaliullin
 */
@ReadAction
@Category("recommended")
@Description("Флаги про показ кнопок для перехода в директ из рекомендованных запросов")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/searchquery/recommended/directTeaserInfo")
public class GetDirectTeaserInfoAction extends Action<GetDirectTeaserInfoRequest, GetDirectTeaserInfoResponse> {

    private final DomainsWithDirectDynamicAdsYDao domainsWithDirectDynamicAdsYDao;
    private final MirrorService2 mirrorService2;
    private final RecommendedQueriesService recommendedQueriesService;

    @Override
    public GetDirectTeaserInfoResponse process(GetDirectTeaserInfoRequest request) {
        WebmasterHostId hostId = request.getHostId();
        boolean showDirectButton = isMainMirror(hostId)
                && foundInDirectTable(hostId)
                && hasRecommendedQueries(hostId);
        return new GetDirectTeaserInfoResponse(showDirectButton);
    }

    private boolean isMainMirror(WebmasterHostId hostId) {
        return mirrorService2.isMainMirror(hostId);
    }

    private boolean foundInDirectTable(WebmasterHostId hostId) {
        String domain = hostId.getASCIIHostname();
        return domainsWithDirectDynamicAdsYDao.containsDomain(domain);
    }

    private boolean hasRecommendedQueries(WebmasterHostId hostId) {
        return recommendedQueriesService.getQueriesCount(hostId, Condition.trueCondition(), RecommendedQueriesCHDao.Include.BOTH) > 0;
    }

}
