#include <balancer/serval/core/config.h>

static NSv::TAction H100(const YAML::Node&, NSv::TAuxData&) {
    class TStreamWithAutomatic100: public NSv::TStreamProxy {
    public:
        using NSv::TStreamProxy::TStreamProxy;

        TMaybe<TStringBuf> Read() noexcept override {
            if (NeedContinue && !NSv::IStream::WriteHead(100)) {
                return {};
            }
            return NSv::TStreamProxy::Read();
        }

        bool WriteHead(NSv::THead& head) noexcept override {
            NeedContinue = false;
            return NSv::TStreamProxy::WriteHead(head);
        }

    private:
        bool NeedContinue = true;
    };

    return [](NSv::IStreamPtr& s) {
        auto* head = s->Head();
        if (!head) {
            return false;
        }
        for (auto range = head->equal_range("expect"); range.first != range.second; range.first++) {
            if (range.first->second == "100-continue") {
                head->erase(range.first);
                s = std::make_shared<TStreamWithAutomatic100>(std::move(s));
                return true;
            }
        }
        return true;
    };
}

SV_DEFINE_ACTION("h100", H100);
