namespace SHH.CameraService;

public class InterceptorPipeline
{
    private readonly IEnumerable<IProtocolInterceptor> _interceptors;

    // 通过依赖注入获取所有注册的拦截器
    public InterceptorPipeline(IEnumerable<IProtocolInterceptor> interceptors)
    {
        _interceptors = interceptors;
    }

    /// <summary>
    /// 执行发送管道
    /// </summary>
    /// <returns>返回处理后的上下文，如果被拦截则返回 null</returns>
    public async Task<ProtocolContext?> ExecuteSendAsync(string protocol, byte[] data)
    {
        var context = new ProtocolContext(protocol, data);

        foreach (var interceptor in _interceptors)
        {
            await interceptor.OnSendingAsync(context);
            if (context.IsBlocked) return null; // 被拦截，终止发送
        }

        return context;
    }

    /// <summary>
    /// 执行接收管道
    /// </summary>
    public async Task<ProtocolContext?> ExecuteReceiveAsync(string protocol, byte[] data)
    {
        var context = new ProtocolContext(protocol, data);

        foreach (var interceptor in _interceptors)
        {
            await interceptor.OnReceivedAsync(context);
            if (context.IsBlocked) return null; // 被拦截，丢弃消息
        }

        return context;
    }
}