using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.NotificationService.Ews;

namespace ZB.MOM.WW.ScadaBridge.NotificationService;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Registers the shared email delivery primitives consumed by the central Notification
    /// Outbox's <c>EmailNotificationDeliveryAdapter</c>: <see cref="NotificationOptions"/>,
    /// <see cref="OAuth2TokenService"/>, the <see cref="ISmtpClientWrapper"/> factory, and —
    /// for the EWS transport — <see cref="IEwsMailSender"/> with its named HTTP client.
    /// Central-only — sites no longer deliver notifications (see
    /// <c>Component-NotificationService.md</c>), and the orphaned site-shaped
    /// <c>NotificationDeliveryService</c> + <c>INotificationDeliveryService</c> contract
    /// was removed. Notification dispatch lives in <c>ZB.MOM.WW.ScadaBridge.NotificationOutbox</c>.
    /// </summary>
    /// <param name="services">The service collection to register into.</param>
    /// <returns>The same <paramref name="services"/> collection, for chaining.</returns>
    public static IServiceCollection AddNotificationService(this IServiceCollection services)
    {
        services.AddOptions<NotificationOptions>()
            .BindConfiguration("ScadaBridge:Notification")
            .ValidateOnStart();
        services.TryAddEnumerable(
            ServiceDescriptor.Singleton<IValidateOptions<NotificationOptions>,
                NotificationOptionsValidator>());

        services.AddHttpClient();
        services.AddSingleton<OAuth2TokenService>();
        services.AddSingleton<Func<ISmtpClientWrapper>>(_ => () => new MailKitSmtpClientWrapper());

        // EWS transport: a named client so the EWS calls get their own handler pool, and a
        // stateless singleton sender (credentials travel per request, never on the client).
        services.AddHttpClient(EwsSoapMailSender.HttpClientName);
        services.TryAddSingleton<IEwsMailSender, EwsSoapMailSender>();

        return services;
    }

    /// <summary>
    /// Registers Akka.NET actors for the notification service (placeholder for actor registration).
    /// </summary>
    /// <param name="services">The service collection to register into.</param>
    /// <returns>The same <paramref name="services"/> collection, for chaining.</returns>
    public static IServiceCollection AddNotificationServiceActors(this IServiceCollection services)
    {
        // Actor registration happens in AkkaHostedService.
        return services;
    }
}
