#pragma once

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

#include <util/generic/vector.h>

namespace NSrvKernel {
    // The library solves the problem of reliable cookie deletion when its exact attributes are unknown.
    // This is needed because the browser actually addresses cookies by a 3-tuple (name, path, domain).
    // See https://st.yandex-team.ru/BALANCER-2827#5f0e12b92177cf00ef23196f for examples.
    // Also note that in a modern browser:
    //  1) To delete a Secure cookie one needs both the Secure flag set and a secure connection.
    //  2) To delete a non-Secure cookie via an insecure connection one needs the Secure flag to be unset.

    struct TDelCookieCtx {
        TStringBuf Name;
        TStringBuf Path; // Only the path part of the url, no scheme, host, query or fragment.
        TStringBuf Host; // A lowercase domain or ip addr
        TMaybe<TStringBuf> Root;
        bool Secure = true;

    public:
        TDelCookieCtx SetPath(TStringBuf path) const noexcept {
            auto res = *this;
            res.Path = path;
            return res;
        }

        TDelCookieCtx SetHost(TStringBuf host) const noexcept {
            auto res = *this;
            res.Host = host;
            return res;
        }
    };

    // /a/b/ -> /a/b -> /a/ ->/a -> / -> /
    TStringBuf ParentPath(TStringBuf path) noexcept;

    TSetCookie DeleteCookieLocal(const TDelCookieCtx& ctx) noexcept;

    void DeleteCookieEveryPath(TVector<TSetCookie>& res, const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;
    TVector<TSetCookie> DeleteCookieEveryPath(const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;

    void DeleteCookieEveryDomain(TVector<TSetCookie>& res, const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;
    TVector<TSetCookie> DeleteCookieEveryDomain(const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;

    void DeleteCookieEveryDomainPath(TVector<TSetCookie>& res, const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;
    TVector<TSetCookie> DeleteCookieEveryDomainPath(const TDelCookieCtx& ctx, bool keepGlobal=false) noexcept;
}
