package ru.yandex.webmaster3.viewer.http.url.checker3;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.WriteAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.url.checker3.UrlCheckRequestParams;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.storage.tools.ToolType;
import ru.yandex.webmaster3.storage.tools.ToolsRequestsLimitService;
import ru.yandex.webmaster3.storage.url.checker3.service.UrlCheckDataBlocksService;
import ru.yandex.webmaster3.viewer.http.AbstractUserAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.uri.WebmasterUriUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

/**
 * @author leonidrom
 */
@Description("Запросить проверку урла")
@WriteAction
@Category("crawl")
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/urlchecker3/startNoHost")
public class StartUrlCheckNoHostAction extends AbstractUserAction<StartUrlCheckNoHostRequest, StartUrlCheckResponse> {
    private final UrlCheckDataBlocksService urlCheckDataBlocksService;
    private final ToolsRequestsLimitService toolsRequestsLimitService;

    @Override
    public StartUrlCheckResponse process(StartUrlCheckNoHostRequest request) {
        UrlCheckRequestParams urlCheckParams = request.getRequestParams();

        URL url;
        try {
            url = processUrl(urlCheckParams.getUrl());
        } catch (Exception e) {
            return new StartUrlCheckResponse.InvalidUrlResponse();
        }

        urlCheckParams = urlCheckParams.withUrl(url.toExternalForm()); // сделаем урл абсолютным

        if (!toolsRequestsLimitService.tryRequest(request.getUserId(), urlCheckParams.getUrl(), ToolType.URL_CHECK)) {
            return new StartUrlCheckResponse.UserLimitReachedResponse();
        }

        var requestId = urlCheckDataBlocksService.sendUrlCheckRequestNoHost(urlCheckParams);
        return new StartUrlCheckResponse.NormalResponse(requestId);
    }

    private URL processUrl(String urlS) throws UserException, MalformedURLException {
        URI uri = WebmasterUriUtils.toOldUri(urlS);;
        if (StringUtils.isEmpty(uri.getPath())) {
            uri = uri.resolve("/");
        }

        return uri.toURL();
    }
}
