using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.ConfigurationDatabase.Repositories;
using ScadaLink.ConfigurationDatabase.Services;

namespace ScadaLink.ConfigurationDatabase;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// Registers the ScadaLinkDbContext with the provided SQL Server connection string.
    /// </summary>
    public static IServiceCollection AddConfigurationDatabase(this IServiceCollection services, string connectionString)
    {
        services.AddDbContext<ScadaLinkDbContext>(options =>
            options.UseSqlServer(connectionString)
                .ConfigureWarnings(w => w.Ignore(
                    Microsoft.EntityFrameworkCore.Diagnostics.RelationalEventId.PendingModelChangesWarning)));

        services.AddScoped<ISecurityRepository, SecurityRepository>();
        services.AddScoped<ICentralUiRepository, CentralUiRepository>();
        services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
        services.AddScoped<IDeploymentManagerRepository, DeploymentManagerRepository>();
        services.AddScoped<ISiteRepository, SiteRepository>();
        services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
        services.AddScoped<INotificationRepository, NotificationRepository>();
        services.AddScoped<IInboundApiRepository, InboundApiRepository>();
        services.AddScoped<IAuditService, AuditService>();
        services.AddScoped<IInstanceLocator, InstanceLocator>();

        services.AddDataProtection()
            .PersistKeysToDbContext<ScadaLinkDbContext>();

        return services;
    }

    /// <summary>
    /// Registers the ScadaLinkDbContext with no connection string (for backward compatibility / Phase 0 stubs).
    /// This overload is a no-op placeholder; callers should migrate to the overload that accepts a connection string.
    /// </summary>
    public static IServiceCollection AddConfigurationDatabase(this IServiceCollection services)
    {
        // Retained for backward compatibility during migration.
        // Site nodes do not use the configuration database, so this is intentionally a no-op.
        return services;
    }
}
