#include <balancer/kernel/cookie/gdpr/cookie_type.h>
#include <balancer/kernel/cookie/gdpr/cookie_registry.h>
#include <balancer/kernel/cookie/gdpr/gdpr.cfgproto.pb.h>

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

#include <util/string/subst.h>

using namespace NGdprCookie;

Y_UNIT_TEST_SUITE(TGdprCookieRegistryTest) {
    Y_UNIT_TEST(TestRealRegistry) {
        InitCookieRegistry(
        // TODO(velavokr): turns out this check is really slow under sanitizers.
#ifdef _san_enabled_
            false
#else
            true
#endif
        );
        for (auto [c, t] : std::initializer_list<std::pair<TString, TString>>{
            {"yandexuid", "tech"},
            {"i", "tech"},
            {"gdpr", "tech"},
            {"is_gdpr", "tech"},
            {"is_gdpr_b", "tech"},
            {"gdpr_popup", "tech"},
        }) {
            UNIT_ASSERT_VALUES_EQUAL(CookieDescr(c).name(), c);
            UNIT_ASSERT_VALUES_EQUAL(ToString(CookieDescr(c).type()), t);
            UNIT_ASSERT_VALUES_EQUAL(ToString(CookieType(c)), t);
        }

        UNIT_ASSERT(!CookieDescr("BALANCER_NO_SUCH_COOKIE").name());
        UNIT_ASSERT_VALUES_EQUAL(CookieDescr("BALANCER_NO_SUCH_COOKIE").type(), ECookieType::Other);
        UNIT_ASSERT_VALUES_EQUAL(CookieType("BALANCER_NO_SUCH_COOKIE"), ECookieType::Other);
    }

    Y_UNIT_TEST(TestConflictDetection) {
        {
            TCookies cfg;
            cfg.cookies().resize(2);
            cfg.cookies()[0].set_name_pattern(".a");
            cfg.cookies()[1].set_name_pattern("a.");

            UNIT_ASSERT_EXCEPTION_CONTAINS(TCookieRegistry(cfg, true), yexception, "Conflict in cookie name patterns");
        }
        {
            TCookies cfg;
            cfg.cookies().resize(2);
            cfg.cookies()[0].set_name("aa");
            cfg.cookies()[1].set_name_pattern("..");

            UNIT_ASSERT_EXCEPTION_CONTAINS(TCookieRegistry(cfg, true), yexception, "Conflict in cookie name patterns");
        }
    }

    Y_UNIT_TEST(TestPlainName) {
        TCookies cfg;
        cfg.cookies().resize(2);
        cfg.cookies()[0].set_name("a.");
        cfg.cookies()[0].set_type(ECookieType::Analytic);
        cfg.cookies()[1].set_name(".a");

        TCookieRegistry reg(cfg, true);

        UNIT_ASSERT_VALUES_EQUAL(reg.Get("a.").name(), "a.");
        UNIT_ASSERT_VALUES_EQUAL(reg.Get("a.").type(), ECookieType::Analytic);
        UNIT_ASSERT_VALUES_EQUAL(reg.Get(".a").name(), ".a");
        UNIT_ASSERT_VALUES_EQUAL(reg.Get(".a").type(), ECookieType::Other);
        UNIT_ASSERT(!reg.Get("aa").name());
        UNIT_ASSERT_VALUES_EQUAL(reg.Get("aa").type(), ECookieType::Other);
    }
}
