#pragma once

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

namespace NSaas {

    class TKpsShardingRule : public TShardsDispatcher::IShardingRule {
    public:
        TKpsShardingRule(const TShardsDispatcher::TContext& context);

        using TShardsDispatcher::IShardingRule::GetShard;
        virtual NSearchMapParser::TShardIndex GetShard(const TStringBuf& url, TKeyPrefix kps) const override;
        virtual bool CheckMessage(const NRTYServer::TMessage& message, TString& error) const override;
        virtual bool CheckSearchInterval(TStringBuf url, TKeyPrefix kps, const TInterval<NSearchMapParser::TShardIndex>& interval) const override;

        virtual void EnumerateIntervals(TStringBuf url, TKeyPrefix kps, const TShardIntervals& sortedIntervals,
                                        IShardIntervalCallback& callback) const override;

        NSearchMapParser::TShardIndex GetComplexShard(TKeyPrefix prefix, const TStringBuf& url) const;
        NSearchMapParser::TShardIndex GetComplexShard(TKeyPrefix prefix, const NSearchMapParser::TShardIndex urlShard) const;
        static NSearchMapParser::TShardIndex GetPrefixShard(TKeyPrefix prefix, const TShardsDispatcher::TContext& context);

    private:
        class TKeysScanner;
        static TShardsDispatcher::IShardingRule::TFactory::TRegistrator<TKpsShardingRule> Registrator;

        TInterval<NSearchMapParser::TShardIndex> GetShardingInterval(NSearchMapParser::TShardIndex shard) const;
    };
}
