using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
namespace ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
///
/// Dependency-injection helpers that wire up the ZB.MOM.WW API-key authentication provider
/// from configuration. These compose the SQLite-backed stores and the configuration-backed
/// pepper provider so a consuming app registers the verifier with a single call.
///
public static class ApiKeyServiceCollectionExtensions
{
///
/// Registers API-key authentication: binds from the
/// configuration section at , wires up the SQLite-backed
/// stores and the configuration-backed pepper provider, and registers
/// .
///
/// The service collection to add to.
/// The application configuration.
/// Path of the configuration section holding the API-key options.
/// The same instance, for chaining.
public static IServiceCollection AddZbApiKeyAuth(
this IServiceCollection services,
IConfiguration config,
string sectionPath)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(config);
ArgumentException.ThrowIfNullOrWhiteSpace(sectionPath);
services.Configure(config.GetSection(sectionPath));
// The pepper provider reads the live IConfiguration on each call. In an ASP.NET Core
// host IConfiguration is already registered; register the caller-supplied instance here
// (TryAdd, so the host's own registration wins when present) so the provider resolves
// even in a bare ServiceCollection.
services.TryAddSingleton(config);
services.TryAddSingleton();
// One connection factory targets the configured SQLite path. Singleton: it is
// stateless aside from the path and opens a fresh connection per operation.
services.TryAddSingleton(sp =>
new AuthSqliteConnectionFactory(
sp.GetRequiredService>().Value.SqlitePath));
services.TryAddSingleton(sp =>
new SqliteApiKeyStore(sp.GetRequiredService()));
services.TryAddSingleton(sp =>
new SqliteApiKeyAdminStore(sp.GetRequiredService()));
services.TryAddSingleton(sp =>
new SqliteApiKeyAuditStore(sp.GetRequiredService()));
services.TryAddSingleton(sp =>
new ApiKeyVerifier(
sp.GetRequiredService>().Value,
sp.GetRequiredService(),
sp.GetRequiredService()));
// Migrator: the SQLite implementation is the default; a provider package that registers
// IApiKeyStoreMigrator (and the three stores) BEFORE this call displaces it — that is the
// whole mechanism by which AddZbApiKeyAuthSqlServer swaps the backend.
services.TryAddSingleton(sp =>
new SqliteAuthStoreMigrator(sp.GetRequiredService()));
services.TryAddSingleton(sp => sp.GetRequiredService());
// Hosted service that runs migrations on startup when ApiKeyOptions.RunMigrationsOnStartup.
services.AddHostedService();
return services;
}
}