#include "handler.h"

namespace NHeadersForwarder {

    void TSimpleHandler::ApplyExt(THeaders& headers) const noexcept {
        THeaders newHeaders = headers.UseBuffer();
        THashSet<TString> weakHeaders;

        for (const auto& header: headers) {
            TString headerLowerCase = header.first.AsString();
            headerLowerCase.to_lower();

            if (HeadersToDelete_.contains(headerLowerCase)) {
                continue;
            }

            newHeaders.Add(header.first, std::move(header.second));

            auto it = HeadersToCreate_.find(headerLowerCase);
            if (it != HeadersToCreate_.cend()) {
                const TValueToCreate& value = it->second;
                if (value.Weak) {
                    weakHeaders.insert(std::move(headerLowerCase));
                }
            }
        }

        for (const auto& headerToCreate : HeadersToCreate_) {
            const TString& headerLowerCase = headerToCreate.first;
            const TValueToCreate& value = headerToCreate.second;

            if (value.Weak && weakHeaders.contains(headerLowerCase)) {
                continue;
            }

            newHeaders.Add(value.Name, value.Value);
        }

        headers.Swap(newHeaders);
    }
}
