#include "p_gdpr_server_cookie.h"

#include <balancer/kernel/cookie/gdpr/gdpr.h>

namespace NModCookiePolicy {
    TPolicyGdprServerCookie::TPolicyGdprServerCookie(TString name, const TPolicyGdprServerCookieCfg& cfg)
        : ICookiePolicy(name, cfg.mode())
        , Cfg_(cfg)
    {
        NGdprCookie::InitCookieRegistry(false);
    }

    bool TPolicyGdprServerCookie::MatchRequest(const TPolicyArgs& args) const noexcept {
        return args.Descr.Properties->Gdpr.Value.IsGdpr
            && args.Descr.Properties->Gdpr.Value.Mode != EGdpr::KeepAll;
    }

    bool TPolicyGdprServerCookie::MatchResponseCookie(const TSetCookie& c, const TPolicyArgs& args) const noexcept {
        // A permanent cookie which is not a deletion
        return (c.Expires || c.MaxAge) && !HasDeletion(c, args.Descr.Properties->Start);
    }

    TMaybe<ICookiePolicy::TAction> TPolicyGdprServerCookie::ApplyToResponseCookie(
        TResponseCookieView c, const TPolicyArgs& args) const noexcept
    {
        const auto& cc = c.Const();
        const auto mode = args.Descr.Properties->Gdpr.Value.Mode;

        if (!NGdprCookie::KeepCookie(args.CookieClassifier.GetCookieType(cc.Name), mode)) {
            return TAction{
                .Reasons={EResponseCookieReason::GdprDelete},
                .Action=ECookieAction::Drop
            };
        }
        return Nothing();
    }
}
