using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using MongoDB.Driver;

namespace Insight.Server.Network.Handlers.Agent
{
    public class SystemInfoHandler : IAgentMessageHandler<AgentSession>
    {
        private readonly IMongoDatabase _database;

        public SystemInfoHandler(IMongoDatabase database)
        {
            _database = database;
        }

        public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IAgentMessage
        {
            if (message is SystemInfo systemInfo)
            {
                await OnSystemInfoAsync(sender, systemInfo, cancellationToken);
            }
        }

        private async ValueTask OnSystemInfoAsync(AgentSession session, SystemInfo? system, CancellationToken cancellationToken)
        {
            var agentEntity = await _database.Agent().Find(Builders<AgentEntity>.Filter.Eq(p => p.Id, session.Id)).FirstOrDefaultAsync(cancellationToken);
            if (agentEntity is null) return;

            var hostEntity = await _database.Host().Find(Builders<HostEntity>.Filter.Eq(p => p.Agent, agentEntity.Id)).FirstOrDefaultAsync(cancellationToken);
            if (hostEntity is null) return;

            var date = DateTime.Now;

            await _database.HostSystem().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders<HostSystemEntity>.Update
                .SetOnInsert(p => p.Insert, date)
                .SetOnInsert(p => p.Host, hostEntity.Id)
                .Set(p => p.Update, date)
                .Set(p => p.BootUpTime, system.LastBootUpTime)
                .Set(p => p.LocalTime, system.LocalDateTime)
                .Set(p => p.Processes, system.Processes)
                .Set(p => p.License, system.License), new UpdateOptions
                {
                    IsUpsert = true
                }, cancellationToken);
        }
    }
}