#include "gdpr_controls.h"
#include "utils.h"

namespace NModCookiePolicy {

    TIsGdprBFilter::TIsGdprBFilter(const TIsGdprBFilterCfg& fltr) noexcept {
        for (auto&& item : fltr.items()) {
            if (item.has_tstamp_secs_begin() && item.has_tstamp_secs_end()) {
                TstampRanges_.insert({
                    TInstant::Seconds(item.tstamp_secs_end()),
                    TInstant::Seconds(item.tstamp_secs_begin())
                });
            }
            if (item.has_balancer_ver_hash()) {
                BalancerVerHashes_.insert(item.balancer_ver_hash());
            }
        }
    }

    bool TIsGdprBFilter::Match(const NGdprCookie::TIsGdprB& isGdprB) const noexcept {
        if (auto it = TstampRanges_.upper_bound(isGdprB.Tstamp); it != TstampRanges_.end()) {
            if (isGdprB.Tstamp >= it->second) {
                return true;
            }
        }
        if (BalancerVerHashes_.contains(isGdprB.BalancerVerHash)) {
            return true;
        }
        return false;
    }


    TGdprControls::TGdprControls(const TGdprControlsCfg& cfg) noexcept
        : Cfg(cfg)
        , BannedIsGdprB(cfg.banned_is_gdpr_b())
        , TechCookieRe(MaybeRe(cfg.tech_cookie_re(), cfg.has_tech_cookie_re()))
    {}


    TCookieClassifier::TCookieClassifier(const TGdprControls& cfg, const TGdprControls* dynCfg) noexcept
        : Cfg_(cfg)
        , DynCfg_(dynCfg)
    {}

    ECookieType TCookieClassifier::GetCookieType(TStringBuf name) const noexcept {
        if (DynCfg_ && DynCfg_->TechCookieRe && Match(*DynCfg_->TechCookieRe, name)) {
            return ECookieType::Tech;
        }
        if (Cfg_.TechCookieRe && Match(*Cfg_.TechCookieRe, name)) {
            return ECookieType::Tech;
        }
        return CookieType(name);
    }

}
