using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace ZB.MOM.WW.ScadaBridge.InboundAPI;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Registers all inbound API services (script executor, route helper, and endpoint filter).
    /// </summary>
    /// <param name="services">The service collection to register into.</param>
    /// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
    public static IServiceCollection AddInboundAPI(this IServiceCollection services)
    {
        // Inbound authentication is handled by the shared
        // ZB.MOM.WW.Auth.ApiKeys verifier (Bearer sbk_<keyId>_<secret>), registered by
        // AddZbApiKeyAuth in the Host composition root. The legacy ApiKeyValidator +
        // peppered IApiKeyHasher and the SQL Server ApiKey store were retired, so this
        // extension no longer registers them.
        services.AddSingleton<InboundScriptExecutor>();
        services.AddScoped<RouteHelper>();

        // WP2.6b: short-TTL cache of resolved ApiMethod rows, sitting in front of the
        // per-request repository fetch in EndpointExtensions. Invalidated by name via
        // ScriptArtifactChangeSubscriber (below) and self-heals via TTL expiry for
        // changes the bus does not cover.
        services.AddSingleton(sp => new ApiMethodCache(
            sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));

        // Routed calls go through the IInstanceRouter seam; the
        // production implementation delegates to CommunicationService.
        services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>();

        // Endpoint filter enforcing the request
        // body size cap and active-node gating for POST /api/{methodName}.
        services.AddSingleton<InboundApiEndpointFilter>();

        // N1: the ApiMethod consumer of the script-artifact invalidation bus.
        // The bus parameter is optional — hosts without a registered
        // IScriptArtifactChangeBus (site roles, plain test hosts) start it as a no-op
        // and the executor's per-request revision check alone keeps handlers fresh.
        services.AddHostedService<ScriptArtifactChangeSubscriber>();

        return services;
    }
}
