#include "plainer_richers.h"

#include <library/cpp/testing/unittest/registar.h>

using namespace NPrivate;

static NJson::TJsonValue BuildHost(const TString& service, const TString& dc, const bool disableSearch, const bool isFailed,
    const bool disableSearchInternal,  const TPlainer::IRicher::TPtr& richerPtr)
{
    NJson::TJsonValue hostJson;
    hostJson["$datacenter$"] = dc;
    hostJson["$datacenter_alias$"] = dc;
    hostJson["disable_search"] = disableSearch;
    hostJson["interval"] = "0-65533";
    hostJson["service"] = service;
    hostJson.InsertValue("result", NJson::JSON_MAP);
    if (!isFailed) {
        hostJson["result"]["docs_in_final_indexes"] = 100;
        hostJson["result"]["docs_in_memory_indexes"] = 200;
        hostJson["result"]["controller_status"] = "Active";
    }
    hostJson["result"]["search_enabled"] = !disableSearchInternal;
    richerPtr->Rich(hostJson);
    return hostJson;
}

void ExpectFacetMap(const NJson::TJsonValue& actual, const TVector<std::pair<TString, i64>>& expected) {
    if (!actual.IsDefined()) {
        UNIT_ASSERT(expected.empty());
        return;
    }
    UNIT_ASSERT(actual.IsString());
    auto parsed = StringToJson(actual.GetStringRobust());
    UNIT_ASSERT(parsed.IsMap());
    auto& actualMap = parsed.GetMapSafe();
    UNIT_ASSERT_EQUAL(actualMap.size(), expected.size());
    for (auto& expectedEntry : expected) {
        UNIT_ASSERT(actualMap.contains(expectedEntry.first));
        UNIT_ASSERT_EQUAL(actualMap.at(expectedEntry.first).GetIntegerRobust(), expectedEntry.second);
    }
}

Y_UNIT_TEST_SUITE(TPlainerRichersTest) {
    Y_UNIT_TEST(RicherFailDomainTaggerTest) {
        const THashSet<TString> perDcSearchingServices({
            "service1",
            "service3"
        });
        TPlainer::IRicher::TPtr richerPtr = MakeIntrusive<TRicherFailDomainTagger>(perDcSearchingServices, "tag");

        UNIT_ASSERT_EQUAL(BuildHost("service0", "MAN", false, false, false, richerPtr)["tag"].GetString(), "ALL");
        UNIT_ASSERT_EQUAL(BuildHost("service1", "MAN", false, false, false, richerPtr)["tag"].GetString(), "MAN");
        UNIT_ASSERT(!BuildHost("service0", "MAN", true, false, false, richerPtr).Has("tag"));
        UNIT_ASSERT(!BuildHost("service0", "MAN", false, true, false, richerPtr).Has("tag"));
        UNIT_ASSERT(!BuildHost("service0", "MAN", false, false, true, richerPtr).Has("tag"));

        ExpectFacetMap(BuildHost("service0", "MAN", false, false, false, richerPtr)["tag_json"], {{"ALL", 1}});
        ExpectFacetMap(BuildHost("service1", "MAN", false, false, false, richerPtr)["tag_json"], {{"MAN", 1}});
        ExpectFacetMap(BuildHost("service0", "MAN", true, false, false, richerPtr)["tag_json"], {{"ALL", 0}});
        ExpectFacetMap(BuildHost("service0", "MAN", false, true, false, richerPtr)["tag_json"], {{"ALL", 0}});
        ExpectFacetMap(BuildHost("service0", "MAN", false, false, true, richerPtr)["tag_json"], {{"ALL", 0}});
    }
}
