using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;

namespace ZB.MOM.WW.OtOpcUa.Server.Tests;

/// <summary>
///     Task #248 — covers the <see cref="DriverFactoryRegistry"/> contract that
///     <see cref="DriverInstanceBootstrapper"/> consumes.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DriverFactoryRegistryTests
{
    private static IDriver FakeDriver(string id, string config) => new FakeIDriver(id);

    [Fact]
    public void Register_then_TryGet_returns_factory()
    {
        var r = new DriverFactoryRegistry();
        r.Register("MyDriver", FakeDriver);

        r.TryGet("MyDriver").ShouldNotBeNull();
        r.TryGet("Nope").ShouldBeNull();
    }

    [Fact]
    public void Register_is_case_insensitive()
    {
        var r = new DriverFactoryRegistry();
        r.Register("Galaxy", FakeDriver);
        r.TryGet("galaxy").ShouldNotBeNull();
        r.TryGet("GALAXY").ShouldNotBeNull();
    }

    [Fact]
    public void Register_duplicate_type_throws()
    {
        var r = new DriverFactoryRegistry();
        r.Register("Galaxy", FakeDriver);
        Should.Throw<InvalidOperationException>(() => r.Register("Galaxy", FakeDriver));
    }

    [Fact]
    public void Register_null_args_rejected()
    {
        var r = new DriverFactoryRegistry();
        Should.Throw<ArgumentException>(() => r.Register("", FakeDriver));
        Should.Throw<ArgumentNullException>(() => r.Register("X", null!));
    }

    [Fact]
    public void RegisteredTypes_returns_snapshot()
    {
        var r = new DriverFactoryRegistry();
        r.Register("A", FakeDriver);
        r.Register("B", FakeDriver);
        r.RegisteredTypes.ShouldContain("A");
        r.RegisteredTypes.ShouldContain("B");
    }

    private sealed class FakeIDriver(string id) : IDriver
    {
        public string DriverInstanceId => id;
        public string DriverType => "Fake";
        public Task InitializeAsync(string _, CancellationToken __) => Task.CompletedTask;
        public Task ReinitializeAsync(string _, CancellationToken __) => Task.CompletedTask;
        public Task ShutdownAsync(CancellationToken _) => Task.CompletedTask;
        public Task FlushOptionalCachesAsync(CancellationToken _) => Task.CompletedTask;
        public DriverHealth GetHealth() => new(DriverState.Healthy, null, null);
        public long GetMemoryFootprint() => 0;
    }
}
