using Insight.Web.Interfaces;
using Insight.Web.Messages;
using System.Net.Sockets;
using Vaitr.Network;

namespace Insight.Web.Network;

public class WebSession(IEnumerable<IWebMessageHandler<WebSession>> handlers, Socket socket, Stream stream, TcpConnectionOptions options, MemPackSerializer serializer, ILogger<WebSession> logger)
    : TcpSession<MemPackSerializer, IWebMessage>(socket, stream, options, serializer, logger)
{
    private readonly IEnumerable<IWebMessageHandler<WebSession>> _handlers = handlers;

    protected override async ValueTask OnReceivedAsync(PacketContext<IWebMessage> context, CancellationToken cancellationToken)
    {
        await base.OnReceivedAsync(context, cancellationToken);

        foreach (var handler in _handlers)
        {
            try
            {
                await handler.HandleAsync(this, context.Data, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogWarning("Web ({ep?}) {ex}", RemoteEndPoint, ex.ToString());
            }
        }
    }
}