#pragma once

#include <string>
#include <unordered_map>
#include <memory>
#include "ChannelHandler.h"

class ChannelPipeline {
public:
    // 添加 handler，key 为名称
    void addHandler(const std::string& name, std::shared_ptr<ChannelHandler> handler) {
        handlers_[name] = std::move(handler);
    }

    // 删除 handler
    void removeHandler(const std::string& name) {
        handlers_.erase(name);
    }

    // 顺序调用所有 handler 的 handle() 方法
    void process(const std::shared_ptr<WebsocketSession>& session, const Message& msg) {
        for (auto& [name, handler] : handlers_) {
            try {
                handler->handle(session, msg);
            } catch (const std::exception& e) {
                spdlog::error("[Pipeline] Handler '{}' error: {}", name, e.what());
                // 发生错误时可选择中断或继续处理
                break;
            }
        }
    }

    // 当连接关闭时，通知所有 handler
    void fireChannelInactive(const std::shared_ptr<WebsocketSession>& session) {
        for (auto& [name, handler] : handlers_) {
            try {
                handler->channelInactive(session);
            } catch (const std::exception& e) {
                spdlog::error("[Pipeline] Handler '{}' channelInactive: {}", name, e.what());
            }
        }
    }

private:
    std::unordered_map<std::string, std::shared_ptr<ChannelHandler>> handlers_;
};
