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

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.feeds.feed.NativeFeedSccStatus;
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.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.notifications.service.UserNotificationSettingsService;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDomainSettingsYDao;
import ru.yandex.webmaster3.storage.turbo.dao.TurboInvalidCartDomainsYDao;
import ru.yandex.webmaster3.storage.turbo.dao.scc.TurboSccService;
import ru.yandex.webmaster3.storage.turbo.dao.scc.model.TurboSccPremoderationStatus;
import ru.yandex.webmaster3.storage.turbo.service.TurboFeedsService;
import ru.yandex.webmaster3.storage.user.notification.UserEmailSettings;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

import static ru.yandex.webmaster3.storage.turbo.dao.scc.TurboSccService.SCC_DEADLINE;

/**
 * ishalaru
 * 18.09.2020
 **/
@ReadAction
@Category("turbo")
@Slf4j
@Component("/turbo/scc/status")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class GetSccStatusAction extends AbstractUserVerifiedHostAction<GetSccStatusAction.Request,
        GetSccStatusAction.Response> {

    private final TurboDomainSettingsYDao turboDomainSettingsYDao;
    private final TurboFeedsService turboFeedsService;
    private final UserNotificationSettingsService userNotificationSettingsService;
    private final TurboInvalidCartDomainsYDao turboInvalidCartDomainsYDao;

    @Override
    public Response process(Request request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        List<TurboFeedSettings> feeds = turboFeedsService.getFeeds(domain);

        final TurboHostSettings settings = turboDomainSettingsYDao.getSettings(domain);
        TurboSccService.FrontModerationStatus status;
        if (turboInvalidCartDomainsYDao.isInvalidCart(domain)) {
            status = TurboSccService.FrontModerationStatus.INVALID_OUTER_CART;
        } else {
            status = TurboSccService.getFrontModerationStatus(settings, feeds);
        }

        List<TurboFeedSettings> ymlFeeds =
                feeds.stream().filter(x -> x.getType() == TurboFeedType.YML)
                        .toList();

        Optional<DateTime> maxEndScc = ymlFeeds.stream()
                .map(TurboFeedSettings::getTimeScc)
                .filter(Objects::nonNull)
                .max(DateTime::compareTo);

        Optional<DateTime> maxAddTime = ymlFeeds.stream()
                .map(TurboFeedSettings::getAddDate)
                .filter(Objects::nonNull)
                .max(DateTime::compareTo);

        DateTime modificationTs = maxEndScc.orElse(maxAddTime.orElse(null));

        List<TurboSccPremoderationStatus.PremoderationProblem> premoderationProblems = feeds.stream()
                .filter(x -> x.getStatus() == NativeFeedSccStatus.FAILED
                        || x.getStatus() == NativeFeedSccStatus.DISABLED_BY_PINGER
                        || x.getStatus() == NativeFeedSccStatus.BANNED)
                .map(TurboFeedSettings::getErrorScc)
                .filter(Objects::nonNull)
                .map(TurboSccPremoderationStatus.PremoderationProblem::new)
                .toList();

        List<TurboSccPremoderationStatus.PremoderationItem> result =
                premoderationProblems.isEmpty() ?
                        List.of() :
                        List.of(new TurboSccPremoderationStatus.PremoderationItem(premoderationProblems));

        final List<TurboSccPremoderationStatus.TurboPremodCategoryType> categories = List.of();
        final UserEmailSettings emailSettingsUI =
                userNotificationSettingsService.getEmailSettingsUI(request.getUserId());
        final String email = emailSettingsUI.getEmailInfo().isVerified() ? emailSettingsUI.getEmailInfo().getEmail()
                : null;
        return new Response.NormalResponse(modificationTs, status, result, false, categories, email);
    }

    public static class Request extends AbstractUserVerifiedHostRequest {

    }

    public static abstract class Response implements ActionResponse {

        @Value
        public static class NormalResponse extends GetSccStatusAction.Response implements ActionResponse.NormalResponse {
            DateTime moderationDateTime;
            TurboSccService.FrontModerationStatus status;
            List<TurboSccPremoderationStatus.PremoderationItem> items;
            boolean hasYmlActiveFeeds;
            List<TurboSccPremoderationStatus.TurboPremodCategoryType> categories;
            String email;

            public DateTime getSccDeadline() {
                return SCC_DEADLINE;
            }
        }
    }
}
