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_domain.FeedDomainInfo;
import ru.yandex.webmaster3.core.feeds.feed_domain.FeedDomainSccStatus;
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.FeedsDomainInfoYDao;

/**
 * Created by kravchenko99 on 01/10/2020.
 */
@Slf4j
@WriteAction
@Category("feeds")
@Description("Результат fullScc")
@Component("/feeds/fullScc/set")
@ActionInternalGrant(InternalGrant.FEEDS)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SetFullSccResultAction extends
        InternalAction<SetFullSccResultAction.Request, SetFullSccResultAction.Response> {

    private final FeedsDomainInfoYDao feedsDomainInfoYDao;

    @Override
    public Response process(Request request) {
        FeedDomainInfo feedDomainInfo = feedsDomainInfoYDao.findById(request.businessId);
        log.info("Abo results for businessId - {}, with status - {}, and comment - {}",
                request.businessId, request.status, request.errorComment);
        if (feedDomainInfo == null) {
            throw new IllegalArgumentException("Unexpected businessId - {}" + request.businessId);
        }

        var newDomainStatus = switch (request.status) {
            case "FAIL" -> FeedDomainSccStatus.FAILED;
            case "PASS" -> FeedDomainSccStatus.SUCCESS;
            case "NO_PLACEMENT" -> FeedDomainSccStatus.BANNED;
            default -> throw new IllegalArgumentException("Unexpected status - " + request.status);
        };
        FeedDomainInfo newInfo = feedDomainInfo.toBuilder()
                .status(newDomainStatus)
                .finishSccTimestamp(DateTime.now())
                .errorScc(request.errorComment)
                .build();

        feedsDomainInfoYDao.update(newInfo);

        return new Response();
    }


    @Setter(onMethod_ = @RequestQueryProperty(required = true))
    public static final class Request extends InternalRequest {
        long businessId;
        String status;
        String errorComment;
    }


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

}
