package ru.yandex.webmaster3.streamer.feeds.mbi;

import java.util.Collections;

import com.google.common.base.Strings;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.market.core.logbroker.PreModerationCheckResultOuterClass.PreModerationCheckResult;
import ru.yandex.webmaster3.core.feeds.feed.NativeFeedInfo2;
import ru.yandex.webmaster3.core.feeds.feed.NativeFeedSccStatus;
import ru.yandex.webmaster3.core.logbroker.reader.IDataProcessing;
import ru.yandex.webmaster3.core.logbroker.reader.MessageContainer;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.storage.feeds.FeedsNative2YDao;
import ru.yandex.webmaster3.storage.feeds.FeedsService;
import ru.yandex.webmaster3.storage.turbo.service.TurboFeedsService;

/**
 * Created by Oleg Bazdyrev on 31/08/2021.
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PreModerationCheckResultsProcessing implements IDataProcessing {
    private final FeedsService feedsService;
    private final TurboFeedsService turboFeedsService;
    private final FeedsNative2YDao feedsNative2YDao;

    @Override
    public void process(MessageContainer messageContainer) {
        for (byte[] rawMessage : messageContainer.getRawMessages()) {
            try {
                PreModerationCheckResult result = PreModerationCheckResult.parseFrom(rawMessage);
                log.info("Got premoderation result for businessId = {} and partnerId = {} and status = {}", result.getBusinessId(), result.getPartnerId(), result.getStatus());
                NativeFeedInfo2 feedInfo = feedsNative2YDao.getById(result.getBusinessId(), result.getPartnerId());
                TurboFeedSettings turboById = feedsService.findTurboById(result.getBusinessId(), result.getPartnerId());
                if (turboById == null && feedInfo == null) {
                    log.warn("Domain info for businessId = {} and partnerId = {} is not found", result.getBusinessId(), result.getPartnerId());
                }
                NativeFeedSccStatus status = convertStatus(result.getStatus());
                if (feedInfo != null) {
                    NativeFeedSccStatus statusScc = status;
                    if (statusScc == NativeFeedSccStatus.IN_PROGRESS) {
                        continue;
                    }
                    NativeFeedSccStatus oldStatusScc = feedInfo.getStatusScc();
                    var builder = feedInfo.toBuilder()
                            .statusScc(statusScc)
                            .sccFinishTimestamp(DateTime.now());

                    if ((statusScc == NativeFeedSccStatus.DISABLED_BY_PINGER ||
                            statusScc == NativeFeedSccStatus.FAILED ||
                            statusScc == NativeFeedSccStatus.BANNED) && !Strings.isNullOrEmpty(result.getError())) {
                        builder.errorsScc(Collections.singletonList(result.getError()));
                    }
                    // update
                    feedsNative2YDao.update(builder.build());
                    if (statusScc == NativeFeedSccStatus.FAILED && oldStatusScc != NativeFeedSccStatus.FAILED) {
                        feedsService.sendFailedSccMessage(feedInfo.getDomain(), feedInfo.getUrl());
                    }
                    if (statusScc == NativeFeedSccStatus.BANNED && oldStatusScc != NativeFeedSccStatus.BANNED) {
                        feedsService.sendBannedSccMessage(feedInfo.getDomain(), feedInfo.getUrl());
                    }
                    if (statusScc == NativeFeedSccStatus.DISABLED_BY_PINGER && oldStatusScc == NativeFeedSccStatus.SUCCESS) {
                        feedsService.sendPingerDisableMessage(feedInfo.getDomain(), feedInfo.getUrl());
                    }
                    if (statusScc == NativeFeedSccStatus.SUCCESS && oldStatusScc == NativeFeedSccStatus.DISABLED_BY_PINGER) {
                        feedsService.sendPingerEnableMessage(feedInfo.getDomain(), feedInfo.getUrl());
                    }
                }
                if (turboById != null && status != NativeFeedSccStatus.UNKNOWN) {
                    boolean active =
                            status == NativeFeedSccStatus.FAILED ||
                                    status == NativeFeedSccStatus.DISABLED_BY_PINGER ||
                                    status == NativeFeedSccStatus.BANNED ?
                                    false : turboById.isActive();
                    TurboFeedSettings newTurboInfo =
                            turboById.toBuilder()
                                    .status(status)
                                    .errorScc(result.getError())
                                    .timeScc(DateTime.now())
                                    .active(active)
                                    .build();
                    turboFeedsService.insertFeed(newTurboInfo);
                }
            } catch (InvalidProtocolBufferException e) {
                log.error("Bad protobuf message", e);
                throw new RuntimeException(e);
            }
        }
        messageContainer.commit();
    }

    private static NativeFeedSccStatus convertStatus(PreModerationCheckResult.Status status) {
        return switch (status) {
            case NEW -> NativeFeedSccStatus.IN_PROGRESS;
            case OK -> NativeFeedSccStatus.SUCCESS;
            case ERROR -> NativeFeedSccStatus.FAILED;
            case REVOKE -> NativeFeedSccStatus.BANNED;
            case UNRECOGNIZED -> NativeFeedSccStatus.UNKNOWN;
            case PINGER -> NativeFeedSccStatus.DISABLED_BY_PINGER;
        };
    }
}
