#include "replier.h"
#include "cgi.h"
#include "auth.h"

#include <saas/searchproxy/logging/error_log.h>
#include <saas/searchproxy/logging/access_log.h>
#include <saas/searchproxy/logging/incoming_log.h>
#include <saas/searchproxy/unistat_signals/signals.h>

#include <saas/library/searchserver/exception.h>

void NSearchProxy::TCommonReplierFeatures::OnRequestExpired(const int httpCode, const TString& proxyType, IReplyContext::TPtr context) {
    if (context) {
        TExtendedReplyContext erc(context.Get());
        erc.SetMetaSearchType(proxyType);
        erc.SetProcessingStartTime(Now());
        erc.MarkTimeouted(true);
        erc.SetHttpStatus(httpCode);
        erc.SetReportStartTime(Now());
        TSaasSearchProxySignals::DoUnistatRecord(erc);
        NSearchProxy::NLogging::TErrorLog::Log(context->GetRequestId(), context->GetRequestData(), "request timeout");
    }
}

void NSearchProxy::TCommonReplierFeatures::OnAccessDenied(const NSaas::TNotAuthorizedInfo& auth, const TString& proxyType, IReplyContext::TPtr context) {
    if (context) {
        LogAccessDenied(auth, proxyType, *context);
    }
}

void NSearchProxy::TCommonReplierFeatures::OnQueueFailure(IReplyContext::TPtr context, const int httpCode) {
    if (context) {
        const TString& service = context->GetRequestData().CgiParam.Get(NSearchProxyCgi::service);
        TSaasSearchProxySignals::DoUnistatUnavailable(service);
        NSearchProxy::NLogging::TErrorLog::Log(context->GetRequestId(), context->GetRequestData(), "cannot queue request");
        if (httpCode) {
            MakeErrorPage(context, httpCode, "Cannot queue request");
        }
    }
}
