package ru.yandex.webmaster3.viewer.http.turbo.dashboard;

import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import org.jetbrains.annotations.NotNull;
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.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.feeds.FeedsNative2YDao;
import ru.yandex.webmaster3.storage.host.service.CommercialOwnersService;
import ru.yandex.webmaster3.storage.turbo.dao.commerce.TurboMarketFeedsYDao;
import ru.yandex.webmaster3.storage.turbo.service.TurboFeedsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

/**
 * ishalaru
 * 23.12.2020
 **/
@ReadAction
@Category("turbo")
@Component("/turbo/ymlSnippet/show")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TurboYMLSnippetTeaserShowAction extends AbstractUserVerifiedHostAction<TurboYMLSnippetTeaserShowAction.Request, TurboYMLSnippetTeaserShowAction.Response> {
    private final TurboFeedsService turboFeedsService;
    private final FeedsNative2YDao feedsNativeYDao;
    private final TurboMarketFeedsYDao turboMarketFeedsYDao;
    private final CommercialOwnersService commercialOwnersService;


    @Override
    public Response process(Request request) {
        @NotNull String domain = WwwUtil.cutWWWAndM(request.getHostId());
        boolean hasExternalShop =
                feedsNativeYDao.hasSuccessfulFeeds(domain) || turboMarketFeedsYDao.hasActiveFeeds(domain);
        boolean isCommercial =
                commercialOwnersService.isCommercialOwner(IdUtils.urlToHostId(WwwUtil.cutWWWAndM(request.getHostId())));
        boolean haveYMLFeeds = turboFeedsService.getFeeds(domain).stream()
                .filter(TurboFeedSettings::isActive).map(TurboFeedSettings::getType).anyMatch(TurboFeedType::isYml);
        return new Response(!hasExternalShop && isCommercial && !haveYMLFeeds);
    }

    public static class Request extends AbstractUserVerifiedHostRequest {

    }

    @Builder
    @Value
    @AllArgsConstructor(onConstructor_ = @JsonCreator)
    public static class Response implements ActionResponse.NormalResponse {
        @Description("Надо отображать тизер или нет")
        boolean showYMLSnippetTeaser;
    }
}
