using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

namespace QYZH.InteractiveMagazine.Infrastructure.RabbitMQ
{
    public static class RabbiteMQExtensions
    {
        /// <summary>
        /// 初始化消息队列，并添加Publisher到IoC容器
        /// </summary>
        /// <remarks>从Configuration读取"RabbbitMQOptions配置项"</remarks>
        public static IServiceCollection AddRabbitMQ(this IServiceCollection services, IConfiguration configuration)
        {
            var rabbitMqSection = configuration.GetSection("RabbitMq");

            if (rabbitMqSection.Exists())
            {
                // 绑定RabbitMQ配置
                services.Configure<RabbitMQOptions>(rabbitMqSection);
                // 注册RabbitMQ连接工厂
                services.AddSingleton<IRabbitMQConnection, RabbitMQConnection>(sp =>
                {
                    var options = sp.GetRequiredService<IOptions<RabbitMQOptions>>().Value;
                    var factory = new ConnectionFactory()
                    {
                        HostName = options.HostName,
                        Port = options.Port,
                        UserName = options.UserName,
                        Password = options.Password,
                        VirtualHost = options.VirtualHost,

                        // 自动恢复配置
                        AutomaticRecoveryEnabled = true,           // 启用自动恢复
                        NetworkRecoveryInterval = TimeSpan.FromSeconds(10), // 每10秒尝试重连
                        // 心跳检测
                        RequestedHeartbeat = TimeSpan.FromSeconds(10),      // 60秒心跳
                        // 其他重要配置
                        TopologyRecoveryEnabled = true,            // 恢复交换机、队列等拓扑结构
                        RequestedConnectionTimeout = TimeSpan.FromSeconds(30),  // 连接超时
                        SocketReadTimeout = TimeSpan.FromSeconds(30),           // 读取超时
                        SocketWriteTimeout = TimeSpan.FromSeconds(30)          // 写入超时
                    };
                    return new RabbitMQConnection(factory);
                });

                // 添加RabbitMQService的服务注册
                services.AddSingleton<IRabbitMQService, RabbitMQService>();
                //services.AddHostedService<TerminalReportService>();
            }

            return services;
        }
    }
}
