using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Agent.Models;
using Insight.Agent.Services;
using Insight.Domain.Constants;

namespace Insight.Agent.Network.Handlers
{
    public class AuthenticationHandler : IAgentMessageHandler<AgentSession>
    {
        public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
        {
            if (message is AuthenticationRequest)
            {
                Config? config = null;

                try
                {
                    config = await Configurator.ReadAsync<Config>(Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
                }
                catch (Exception) { }

                if (config is null)
                {
                    config = new Config { Serial = Guid.NewGuid() };
                    await Configurator.WriteAsync(config, Configuration.DefaultConfig, cancellationToken).ConfigureAwait(false);
                }

                await sender.SendAsync(new Authentication
                {
                    Serial = config.Serial ?? throw new InvalidDataException(nameof(config.Serial)),
                    Version = Configuration.Version,
                    Hostname = Configuration.Hostname
                }, cancellationToken);
            }
        }
    }
}