using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.ConfigurationDatabase;

namespace ScadaLink.ConfigurationDatabase.Tests;

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

        services.AddConfigurationDatabase("DataSource=:memory:");

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

    // 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);
    }
}
