using Microsoft.Extensions.DependencyInjection.Extensions;
using ZB.MOM.WW.Overview.Observability;

namespace ZB.MOM.WW.Overview.Polling;

/// <summary>Registers the polling pipeline.</summary>
public static class PollingServiceCollectionExtensions
{
    /// <summary>Adds the snapshot store, the probe client and the poller.</summary>
    /// <param name="services">The service collection.</param>
    /// <returns>The same collection, for chaining.</returns>
    public static IServiceCollection AddOverviewPolling(this IServiceCollection services)
    {
        ArgumentNullException.ThrowIfNull(services);

        services.TryAddSingleton(TimeProvider.System);
        services.TryAddSingleton<OverviewSnapshotStore>();

        // IMeterFactory comes from AddMetrics, which the default web host already registers; the
        // call is idempotent and makes the dependency explicit for any non-web host.
        services.AddMetrics();
        services.TryAddSingleton<OverviewMetrics>();
        services.TryAddSingleton<PollCycleHeartbeat>();

        services.AddHttpClient(OverviewPollerService.HttpClientName, client =>
        {
            // The per-request CancellationTokenSource in ZbHealthReportClient is the only timeout
            // that should ever fire. Leaving HttpClient's own 100s default in place would let it
            // pre-empt a per-instance override and report "timed out after 3s" for a 100s wait.
            client.Timeout = Timeout.InfiniteTimeSpan;

            // Health bodies are small and must not be served from anywhere but the instance itself.
            client.DefaultRequestHeaders.CacheControl = new() { NoCache = true, NoStore = true };
        });

        services.AddHostedService<OverviewPollerService>();

        return services;
    }
}
