// Licensed to Timothy Schenk under the GNU AGPL Version 3 License.

using System.Diagnostics;
using Continuity.AuthServer.Packets;
using JetBrains.Annotations;
using MassTransit;
using RaiNote.PacketMediator;
using Wonderking.Packets;

namespace Continuity.AuthServer.Consumers;

[UsedImplicitly]
public sealed class PacketConsumer : IConsumer<RawPacket>, IDisposable
{
    private readonly ActivitySource _activitySource;
    private readonly PacketDistributorService<OperationCode, AuthSession> _distributorService;

    public PacketConsumer(PacketDistributorService<OperationCode, AuthSession> distributorService)
    {
        _distributorService = distributorService;
        _activitySource = new ActivitySource(nameof(PacketConsumer));
    }

    public async Task Consume(ConsumeContext<RawPacket> context)
    {
        using var activity = _activitySource?.StartActivity("PacketConsumption");
        activity?.SetTag("PacketId", context.Message.OperationCode.ToString());
        activity?.SetTag("SessionId", context.Message.Session.Id.ToString());
        activity?.SetTag("PacketSize", context.Message.MessageBody.Length);

        await _distributorService.AddPacketAsync(context.Message.MessageBody, context.Message.OperationCode,
            context.Message.Session);
    }

    public void Dispose()
    {
        _activitySource.Dispose();
    }
}