// Copyright 2012-2026 The NATS Authors
// Licensed under the Apache License, Version 2.0

using System.Reflection;
using Shouldly;
using ZB.MOM.NatsNet.Server;
using ZB.MOM.NatsNet.Server.Internal;

namespace ZB.MOM.NatsNet.Server.Tests.Accounts;

public sealed class ResolverDefaultsOpsTests
{
    [Fact]
    public async Task ResolverDefaults_StartReloadClose_ShouldBeNoOps()
    {
        var resolver = new DummyResolver();

        resolver.IsReadOnly().ShouldBeTrue();
        resolver.IsTrackingUpdate().ShouldBeFalse();

        resolver.Start(new object());
        resolver.Reload();
        resolver.Close();

        var jwt = await resolver.FetchAsync("A");
        jwt.ShouldBe("jwt");

        await Should.ThrowAsync<NotSupportedException>(() => resolver.StoreAsync("A", "jwt"));
    }

    [Fact]
    public void UpdateLeafNodes_SubscriptionDelta_ShouldUpdateMaps()
    {
        var acc = new Account { Name = "A" };
        var sub = new Subscription
        {
            Subject = System.Text.Encoding.UTF8.GetBytes("foo"),
            Queue = System.Text.Encoding.UTF8.GetBytes("q"),
            Qw = 2,
        };

        acc.UpdateLeafNodes(sub, 1);

        var rm = (Dictionary<string, int>?)typeof(Account)
            .GetField("_rm", BindingFlags.Instance | BindingFlags.NonPublic)!
            .GetValue(acc);
        rm.ShouldNotBeNull();
        rm!["foo"].ShouldBe(1);

        var lqws = (Dictionary<string, int>?)typeof(Account)
            .GetField("_lqws", BindingFlags.Instance | BindingFlags.NonPublic)!
            .GetValue(acc);
        lqws.ShouldNotBeNull();
        lqws!["foo q"].ShouldBe(2);
    }

    private sealed class DummyResolver : ResolverDefaultsOps
    {
        public override Task<string> FetchAsync(string name, CancellationToken ct = default)
            => Task.FromResult("jwt");
    }
}
