using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
using ZB.MOM.WW.ScadaBridge.Transport.Encryption;
using ZB.MOM.WW.ScadaBridge.Transport.Export;
using ZB.MOM.WW.ScadaBridge.Transport.Import;
using ZB.MOM.WW.ScadaBridge.Transport.Serialization;

namespace ZB.MOM.WW.ScadaBridge.Transport;

public static class ServiceCollectionExtensions
{
    public const string OptionsSection = "ScadaBridge:Transport";

    /// <summary>
    /// Registers the Transport component services: encryptor, manifest builder/validator, serializers, resolver, exporter, importer, and session store.
    /// </summary>
    /// <param name="services">The service collection to register into.</param>
    /// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
    public static IServiceCollection AddTransport(this IServiceCollection services)
    {
        ArgumentNullException.ThrowIfNull(services);
        // Eager startup validation (arch-review 08 §1.5): ValidateOnStart makes a
        // bad ScadaBridge:Transport section — a zero/negative cap, or (critically)
        // a Pbkdf2Iterations below the security floor that would silently weaken
        // bundle key derivation — fail fast at boot with a clear, key-naming
        // message instead of surfacing deep inside the import pipeline.
        services.AddOptions<TransportOptions>().BindConfiguration(OptionsSection).ValidateOnStart();
        services.TryAddEnumerable(
            ServiceDescriptor.Singleton<IValidateOptions<TransportOptions>, TransportOptionsValidator>());
        services.TryAddSingleton(TimeProvider.System);

        // Pipeline building blocks: stateless services live as singletons; the
        // resolver and exporter are scoped because they reach into per-request
        // repository scopes and the scoped DbContext.
        services.AddSingleton<BundleSecretEncryptor>();
        services.AddSingleton<ManifestBuilder>();
        services.AddSingleton<ManifestValidator>();
        services.AddSingleton<BundleSerializer>();
        services.AddSingleton<EntitySerializer>();
        services.AddScoped<DependencyResolver>();
        services.AddScoped<IBundleExporter, BundleExporter>();
        services.AddSingleton<IBundleSessionStore, BundleSessionStore>();
        // T-004: per-IP-per-hour unlock rate limiter — design doc §11. Singleton
        // so the trailing-hour window is shared across every importer scope; the
        // counters live in-memory and reset on host restart (by design).
        services.AddSingleton<BundleUnlockRateLimiter>();
        // T-007: periodic eviction sweep so abandoned sessions clear without
        // needing a fresh Get() to trigger lazy eviction.
        services.AddHostedService<BundleSessionEvictionService>();
        // SemanticValidator is a stateless utility used by ApplyAsync; use
        // TryAdd so a host that already calls AddTemplateEngine() (which
        // registers the same type as Transient) wins. Either registration
        // satisfies the BundleImporter constructor.
        services.TryAddTransient<SemanticValidator>();
        services.AddScoped<IBundleImporter, BundleImporter>();
        // Remaining concrete services added in later tasks.
        return services;
    }
}
