package ru.yandex.webmaster3.viewer.http.searchquery;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.searchquery.QueryId;
import ru.yandex.webmaster3.core.searchquery.viewer.ViewerQuery;
import ru.yandex.webmaster3.storage.searchquery.QueryStatisticsService2;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

import java.util.Collections;
import java.util.Map;

/**
 * @author avhaliullin
 */
@Description("Получить текст запроса по его id")
@ReadAction
@Category("searchquery")
@Component("/searchquery/queryInfo")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class GetQueryInfoAction extends AbstractUserVerifiedHostAction<GetQueryInfoRequest, GetQueryInfoResponse> {
    private final QueryStatisticsService2 queryStatisticsService2;

    @Override
    public GetQueryInfoResponse process(GetQueryInfoRequest request) {
        QueryId queryId = request.getQueryId();
        Map<QueryId, String> queries = queryStatisticsService2.getQueryTexts(
                request.getHostId(),
                request.getSpecialGroup(),
                Collections.singletonList(queryId)
        );
        if (!queries.containsKey(queryId)) {
            return new GetQueryInfoResponse.QueryNotFoundError();
        }
        return new GetQueryInfoResponse.NormalResponse(new ViewerQuery(queryId, queries.get(queryId)));
    }

}
