using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Microsoft.Extensions.Logging;
using System.Net.Sockets;
using Vaitr.Network;

namespace Insight.Agent.Network;

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

    protected override async ValueTask OnReceivedAsync(PacketContext<IAgentMessage> 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("Agent ({ep?}) {ex}", RemoteEndPoint, ex.ToString());
            }
        }
    }
}