#include <search/web/core/rule.h>

#include <library/cpp/cgiparam/cgiparam.h>

struct TServiceShardingRuleContext: IRearrangeRuleContext {
    void DoAdjustClientParams(const TAdjustParams& adjustParams) override {
        if (adjustParams.ClientRequestAdjuster->IsClientEphemeral()) {
            return;
        }

        const TCgiParameters::const_iterator& iter =
            adjustParams.RequestFields.CgiParam.Find(TStringBuf("service"));
        if (iter == adjustParams.RequestFields.CgiParam.end()) {
            adjustParams.ClientRequestAdjuster->ClientDontSendRequest();
            return;
        }

        const TString& descr = adjustParams.SourceGroup();
        const auto services = SplitString(iter->second, ",");
        if (std::find(services.begin(), services.end(), descr) == services.end()) {
            adjustParams.ClientRequestAdjuster->ClientDontSendRequest();
        }
    }
};

struct TServiceShardingRule: IRearrangeRule {
    IRearrangeRuleContext* DoConstructContext() const override {
        return new TServiceShardingRuleContext;
    }
};

IRearrangeRule* CreateServiceShardingRule(const TString&, const TSearchConfig&)
{
    return new TServiceShardingRule;
}

REGISTER_REARRANGE_RULE(ServiceSharding, CreateServiceShardingRule);
