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 CustomHandler : IMessageHandler<AgentSession>
{
    private readonly ScriptService _scriptService;
    private readonly ILogger<CustomHandler> _logger;

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

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

    private async ValueTask OnRequestAsync(AgentSession sender, Request request, CancellationToken cancellationToken)
    {
        var result = await _scriptService.QueryAsync(request.RequestData);

        await sender.SendAsync(new Response(request)
        {
            ResponseData = result.HadErrors ? result.Errors : result.Data,
            ResponseError = result.HadErrors
        }, cancellationToken);
    }
}