using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;

namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;

public class ServiceCollectionExtensionsTests
{
    [Fact]
    public void AddConfigurationDatabase_WithConnectionString_RegistersRepositoriesAndServices()
    {
        var services = new ServiceCollection();

        services.AddConfigurationDatabase("Server=unused;Database=unused;");

        Assert.Contains(services, d => d.ServiceType == typeof(ITemplateEngineRepository));
        Assert.Contains(services, d => d.ServiceType == typeof(IAuditService));
        Assert.Contains(services, d => d.ServiceType == typeof(IInstanceLocator));
        Assert.Contains(services, d => d.ServiceType == typeof(IAuditLogRepository));
    }

    [Fact]
    public void AddConfigurationDatabase_Configures_RetryingExecutionStrategy()
    {
        // Task 12 (arch-review 04 S5): the central DbContext must survive transient
        // SQL faults. EnableRetryOnFailure installs a non-null ExecutionStrategyFactory
        // on the SqlServer options extension — covering every read-side path (KPI asks,
        // outbox queries, Tracking.Status, execution trees) that previously surfaced
        // transient faults raw.
        var services = new ServiceCollection();
        services.AddConfigurationDatabase("Server=unused;Database=unused;");
        using var sp = services.BuildServiceProvider();

        var options = sp.GetRequiredService<DbContextOptions<ScadaBridgeDbContext>>();

        // EF1001: SqlServerOptionsExtension is an internal EF surface, but it is the
        // only place the retrying-strategy factory is observable — asserting it is the
        // point of this test. Scoped suppression, not a project-wide one.
#pragma warning disable EF1001
        var sqlExt = options.Extensions
            .OfType<Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerOptionsExtension>()
            .Single();

        Assert.NotNull(sqlExt.ExecutionStrategyFactory);
#pragma warning restore EF1001
    }

    // The no-arg overload is [Obsolete(error: true)], so it cannot be referenced directly
    // from source — that is the compile-time guard. Invoke it via reflection to verify the
    // runtime defence-in-depth behaviour.
    private static MethodInfo NoArgOverload =>
        typeof(ServiceCollectionExtensions).GetMethod(
            nameof(ServiceCollectionExtensions.AddConfigurationDatabase),
            BindingFlags.Public | BindingFlags.Static,
            binder: null,
            types: new[] { typeof(IServiceCollection) },
            modifiers: null)!;

    [Fact]
    public void AddConfigurationDatabase_NoArgOverload_FailsFastWithClearMessage()
    {
        // Regression guard for ConfigurationDatabase-003: the parameterless overload must not
        // silently register nothing. Misuse must surface immediately at wire-up time with an
        // actionable message — not later as an opaque DI resolution failure.
        var services = new ServiceCollection();

        var invocation = Assert.Throws<TargetInvocationException>(
            () => NoArgOverload.Invoke(null, new object[] { services }));

        var ex = Assert.IsType<InvalidOperationException>(invocation.InnerException);
        Assert.Contains("connection string", ex.Message, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public void AddConfigurationDatabase_NoArgOverload_IsMarkedObsoleteAsError()
    {
        // The no-op overload must be flagged so misuse is caught at compile time.
        var obsolete = NoArgOverload.GetCustomAttribute<ObsoleteAttribute>();
        Assert.NotNull(obsolete);
        Assert.True(obsolete!.IsError);
    }
}
