using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

public sealed class LocalPagingPublisher
{
    private readonly RabbitMqOptions _opts;
    private readonly ILogger<LocalPagingPublisher> _logger;

    public LocalPagingPublisher(IOptions<RabbitMqOptions> opts, ILogger<LocalPagingPublisher> logger)
    {
        _opts = opts.Value;
        _logger = logger;
    }

    public Task PublishCriticalAsync(LocalClinicalAlert alert, ReplicaEncounter encounter)
    {
        try
        {
            var factory = RabbitMqConnectionFactory.Create(_opts);
            using var conn = factory.CreateConnection("gateway-publisher");
            using var channel = conn.CreateModel();

            var payload = JsonSerializer.Serialize(new
            {
                alertId = alert.Id,
                encounterId = alert.EncounterId,
                details = alert.Details,
                attendingPhysician = encounter.AttendingPhysician
            });

            var body = Encoding.UTF8.GetBytes(payload);
            channel.BasicPublish(
                RabbitMqTopologyProvisioner.Exchange,
                RabbitMqTopologyProvisioner.PagingKey,
                body: body);

            _logger.LogInformation(
                "Published critical alert {AlertId} to paging queue for encounter {EncounterId}",
                alert.Id, alert.EncounterId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "Failed to publish critical alert {AlertId} to paging queue — alert persisted locally",
                alert.Id);
        }

        return Task.CompletedTask;
    }
}
