package ru.yandex.webmaster3.worker.metrika;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemState;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.metrika.counters.CounterBindingStateEnum;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.checklist.data.ProblemSignal;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemsService;
import ru.yandex.webmaster3.storage.events.data.WMCEvent;
import ru.yandex.webmaster3.storage.events.data.WMCEventContent;
import ru.yandex.webmaster3.storage.events.data.events.MetrikaCounterBindingStateChangeEvent;
import ru.yandex.webmaster3.storage.events.service.WMCEventsObserver;

/**
 * @author leonidrom
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MetrikaCounterBindingStateChangeEventsObserver implements WMCEventsObserver {
    private final SiteProblemsService siteProblemsService;

    @Override
    public boolean observe(WMCEvent event) {
        WMCEventContent content = event.getContent();
        if (!(content instanceof MetrikaCounterBindingStateChangeEvent)) {
            return false;
        }

        var stateChangeEvent = (MetrikaCounterBindingStateChangeEvent)content;
        WebmasterHostId domainHostId = IdUtils.urlToHostId(stateChangeEvent.getDomain());
        log.info("Got event for: {}, state: {}", domainHostId, stateChangeEvent.getState());
        if (stateChangeEvent.getState() == CounterBindingStateEnum.APPROVED) {
            // быстро выключим пользователю проблему, не дожидаясь запуска периодической таски
            var problemSignal = new ProblemSignal(SiteProblemTypeEnum.NO_METRIKA_COUNTER_BINDING, SiteProblemState.ABSENT, event.getEventTime());
            siteProblemsService.updateCleanableProblem(domainHostId, problemSignal);
        }

        return true;
    }

    @Override
    public boolean isProcessedLoggingEnabled() {
        return true;
    }
}
