using Akka.Actor;
using Akka.TestKit.Xunit2;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors;
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;
///
/// Arch-review 2026-08-19 P2-5 — the tag-resolution PROBE path did not seed the tags it
/// resolved.
///
///
/// The gap this pins. Both other subscribe paths read each newly advised tag's current
/// value and deliver it (HandleSubscribe carries the seeds back on SubscribeCompleted;
/// ReSubscribeAll re-seeds after a reconnect), because a fresh advise only produces a value
/// on the source's next CHANGE. HandleRetryTagResolution did not. OPC UA masks that with an
/// initial data-change notification on subscription creation, but an MxGateway advise can
/// legitimately return VT_EMPTY — so a STATIC tag that resolved LATE (device still booting,
/// item created after deployment) had no value path at all and its attribute stayed Uncertain for
/// the life of the connection.
///
///
[Collection("DataConnectionManagerActor")]
public class DataConnectionProbeSeedTests : TestKit
{
private const string Tag = "plant/static/setpoint";
private readonly ISiteHealthCollector _health = Substitute.For();
private readonly IDataConnectionFactory _factory = Substitute.For();
private readonly DataConnectionOptions _options = new()
{
ReconnectInterval = TimeSpan.FromMilliseconds(100),
TagResolutionRetryInterval = TimeSpan.FromMilliseconds(150),
WriteTimeout = TimeSpan.FromSeconds(5),
SeedReadMaxAttempts = 1,
SeedReadRetryDelay = TimeSpan.FromMilliseconds(10)
};
private IActorRef CreateConnectionActor(string name, IDataConnection adapter) =>
Sys.ActorOf(Props.Create(() =>
new DataConnectionActor(name, adapter, _options, _health, _factory, "OpcUa")), name);
private bool HasEnteredConnectedState(string connectionName) =>
_health.ReceivedCalls().Any(c =>
c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) &&
c.GetArguments() is [string name, ConnectionHealth.Connected, ..] &&
name == connectionName);
///
/// A tag that fails to resolve on the initial subscribe, resolves on the first probe round,
/// and then never changes again must still reach its subscriber with a Good value.
///
///
/// The adapter here models exactly the MxGateway shape the finding calls out: the advise
/// succeeds on the retry but the subscription callback is NEVER invoked (a VT_EMPTY
/// advise on a static item), so the seed read is the tag's only possible value source.
///
///
/// Fails before the fix: the probe resolved the tag and stopped there — the
/// subscriber received only the Bad-quality resolution-failure push from the initial
/// subscribe, and this fish for a Good value timed out.
///
[Fact]
public void ProbeResolvedTag_IsSeeded_SoAStaticTagLeavesUncertain()
{
const string name = "probe-seed";
var subscribeCalls = 0;
var adapter = Substitute.For();
adapter.ConnectAsync(Arg.Any>(), Arg.Any())
.Returns(Task.CompletedTask);
adapter.Status.Returns(ConnectionHealth.Connected);
adapter.SubscribeAsync(Tag, Arg.Any(), Arg.Any())
.Returns(_ => Interlocked.Increment(ref subscribeCalls) == 1
// Initial subscribe: the device is still booting — a genuine (non
// connection-level) resolution failure, so the tag lands in _unresolvedTags.
? Task.FromException(new KeyNotFoundException("node not found yet"))
// Probe round: the advise succeeds. The callback is deliberately never invoked.
: Task.FromResult("sub-1"));
adapter.ReadAsync(Tag, Arg.Any())
.Returns(new ReadResult(true, new TagValue(42, QualityCode.Good, DateTimeOffset.UtcNow), null));
var actor = CreateConnectionActor(name, adapter);
AwaitCondition(() => HasEnteredConnectedState(name),
TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));
var subscriber = CreateTestProbe();
subscriber.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow));
// The initial subscribe fails: Bad-quality push, then the ack.
subscriber.FishForMessage(_ => true, TimeSpan.FromSeconds(5));
// The probe round resolves the tag; the seed read is the only thing that can now
// deliver a value, because the advise callback never fires for this static item.
var seeded = subscriber.FishForMessage(
m => m.TagPath == Tag && m.Quality == QualityCode.Good, TimeSpan.FromSeconds(10));
Assert.Equal(42, seeded.Value);
Assert.True(Volatile.Read(ref subscribeCalls) >= 2, "the probe round must have re-subscribed the tag");
}
}