using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using ScadaLink.Commons.Types.InboundApi;

namespace ScadaLink.InboundAPI;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddInboundAPI(this IServiceCollection services)
    {
        services.AddScoped<ApiKeyValidator>();
        services.AddSingleton<InboundScriptExecutor>();
        services.AddScoped<RouteHelper>();

        // ConfigurationDatabase-012: API keys are persisted as a deterministic HMAC
        // hash, never as plaintext. The hasher is keyed with a server-side pepper
        // bound from configuration (InboundApiOptions.ApiKeyPepper). Constructing
        // ApiKeyHasher throws if the pepper is missing or weak — so a misconfigured
        // deployment fails fast the first time the hasher is resolved rather than
        // silently hashing with no pepper.
        services.AddSingleton<IApiKeyHasher>(sp =>
        {
            var options = sp.GetRequiredService<IOptions<InboundApiOptions>>().Value;
            return new ApiKeyHasher(options.ApiKeyPepper);
        });

        // InboundAPI-017: routed calls go through the IInstanceRouter seam; the
        // production implementation delegates to CommunicationService.
        services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>();

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

        return services;
    }
}
