using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TakeoutSaaS.Module.Messaging.Abstractions;
using TakeoutSaaS.Module.Messaging.Options;
using TakeoutSaaS.Module.Messaging.Serialization;
using TakeoutSaaS.Module.Messaging.Services;

namespace TakeoutSaaS.Module.Messaging.Extensions;

/// <summary>
/// 消息队列模块注册扩展。
/// </summary>
public static class MessagingServiceCollectionExtensions
{
    /// <summary>
    /// 注册 RabbitMQ 发布/订阅能力。
    /// </summary>
    public static IServiceCollection AddMessagingModule(this IServiceCollection services, IConfiguration configuration)
    {
        var rabbitMqSection = configuration.GetSection("RabbitMQ");
        if (!rabbitMqSection.Exists())
        {
            services.AddSingleton<IMessagePublisher, NoOpMessagePublisher>();
            services.AddSingleton<IMessageSubscriber, NoOpMessageSubscriber>();
            return services;
        }

        // 1. (空行后) 存在 RabbitMQ 配置时才启用真实 MQ 能力（启动时验证配置完整性）
        services.AddOptions<RabbitMqOptions>()
            .Bind(rabbitMqSection)
            .ValidateDataAnnotations()
            .ValidateOnStart();

        services.AddSingleton<JsonMessageSerializer>();
        services.AddSingleton<RabbitMqConnectionFactory>();
        services.AddSingleton<IMessagePublisher, RabbitMqMessagePublisher>();
        services.AddSingleton<IMessageSubscriber, RabbitMqMessageSubscriber>();

        return services;
    }
}
