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 MainboardHandler : IAgentMessageHandler<AgentSession>
    {
        private readonly IMongoDatabase _database;

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

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

        private async ValueTask OnMainboardAsync(AgentSession session, Mainboard mainboard, 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.HostMainboard().UpdateOneAsync(p => p.Host == hostEntity.Id, Builders<HostMainboardEntity>.Update
                .SetOnInsert(p => p.Insert, date)
                .SetOnInsert(p => p.Host, hostEntity.Id)
                .Set(p => p.Update, date)
                .Set(p => p.Name, mainboard?.Manufacturer)
                .Set(p => p.Name, mainboard?.Model)
                .Set(p => p.Serial, mainboard?.Serial)
                .Set(p => p.Bios, mainboard?.BiosManufacturer)
                .Set(p => p.Version, mainboard?.BiosVersion)
                .Set(p => p.Date, mainboard?.BiosDate), new UpdateOptions
                {
                    IsUpsert = true
                }, cancellationToken);
        }
    }
}
