using Insight.Agent.Services;
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging;

namespace Insight.Agent.Network.Handlers;

public class ProxyHandler : IMessageHandler<AgentSession>
{
    private readonly ScriptService _scriptService;
    private readonly ILogger<ProxyHandler> _logger;

    public ProxyHandler(ScriptService scriptService, ILogger<ProxyHandler> logger)
    {
        _scriptService = scriptService;
        _logger = logger;
    }

    public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
    {
        switch (message)
        {
            case Proxy<Request> proxyRequest:
                await OnProxyRequestAsync(sender, proxyRequest, cancellationToken);
                break;
        }
    }

    private async ValueTask OnProxyRequestAsync(AgentSession sender, Proxy<Request> proxyRequest, CancellationToken cancellationToken)
    {
        var result = await _scriptService.QueryAsync(proxyRequest.Message.RequestData);

        await sender.SendAsync(new Proxy<Response>()
        {
            ProxyId = proxyRequest.ProxyId,
            Message = new Response(proxyRequest.Message)
            {
                ResponseData = result.HadErrors ? result.Errors : result.Data,
                ResponseError = result.HadErrors
            }
        }, cancellationToken);
    }
}