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

import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Category;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.storage.niche.NicheQueriesCHDao;
import ru.yandex.webmaster3.storage.niche.NicheRivalQueriesReportCHDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.host.verification.UsersVerifiedHostRequest;

/**
 * Created by Oleg Bazdyrev on 29/07/2021.
 */
@ReadAction
@Category("niche")
@Component("/niche/status")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetNicheStatusAction extends AbstractUserVerifiedHostAction<GetNicheStatusAction.Request, GetNicheStatusAction.Response> {

    private static final long MIN_QUERY_COUNT = 200;
    private static final long MIN_RIVAL_COUNT = 2;

    private final NicheQueriesCHDao nicheQueriesCHDao;
    private final NicheRivalQueriesReportCHDao nicheRivalQueriesReportCHDao;

    @Override
    public Response process(Request request) {
        WebmasterHostId hostId = request.getHostId();
        LocalDate dateTo = LocalDate.now();
        LocalDate dateFrom = dateTo.minusMonths(3);
        long queryCount = nicheQueriesCHDao.countQueries(hostId, dateFrom, dateTo, null, null, null);
        long rivalCount = nicheRivalQueriesReportCHDao.getRivalsCount(hostId, dateFrom, dateTo, null, null, null);
        return new Response(queryCount >= MIN_QUERY_COUNT && rivalCount >= MIN_RIVAL_COUNT);
    }

    public static final class Request extends UsersVerifiedHostRequest {

    }

    @Value
    public static class Response implements ActionResponse.NormalResponse {
        @Description("Доступна ли ниша сайта")
        boolean available;
    }
}
