package ru.yandex.webmaster3.internal.feeds;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
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.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.feeds.feed.NativeFeedInfo2;
import ru.yandex.webmaster3.core.feeds.mbi.MbiService;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.internal.common.InternalAction;
import ru.yandex.webmaster3.internal.common.InternalRequest;
import ru.yandex.webmaster3.internal.common.security.ActionInternalGrant;
import ru.yandex.webmaster3.internal.common.security.InternalGrant;
import ru.yandex.webmaster3.storage.feeds.FeedsNative2YDao;

import static ru.yandex.webmaster3.core.feeds.feed.NativeFeedType.STORES;

/**
 * Created by kravchenko99 on 01/10/2020.
 */
@Slf4j
@WriteAction
@Category("feeds")
@Description("Проставить статус и коммент для магазина")
@Component("/feeds/unisearch/scc/recheck")
@ActionInternalGrant(InternalGrant.FEEDS)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FeedsStartSccAction extends
        InternalAction<FeedsStartSccAction.Request, FeedsStartSccAction.Response> {

    private final FeedsNative2YDao feedsNativeYDao;
    private final MbiService mbiService;

    @Override
    public Response process(Request request) {

        NativeFeedInfo2 nativeFeedInfo2 = feedsNativeYDao.get(request.domain, request.feedUrl);
        if (nativeFeedInfo2 == null) {
            throw new IllegalArgumentException("feed doesn't exists");
        }

        if (nativeFeedInfo2.getType() == STORES) {
            startMbiScc(nativeFeedInfo2);
        } else {
            startUnisearchScc(nativeFeedInfo2);
        }

        return new Response();
    }

    public void startUnisearchScc(NativeFeedInfo2 info) {
        NativeFeedInfo2 newInfo = info
                .toBuilder()
                .sccTimestamp(DateTime.now())
                .build();
        feedsNativeYDao.update(newInfo);
    }

    public void startMbiScc(NativeFeedInfo2 info) {
        mbiService.recheckShop(info.getPartnerId());
    }

    @Setter(onMethod_ = @RequestQueryProperty(required = true))
    public static final class Request extends InternalRequest {
        String domain;
        String feedUrl;
    }


    @Value
    public static class Response implements ActionResponse.NormalResponse {
    }

}
