using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Modbus.Cli.Commands;

namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Cli.Tests;

/// <summary>
///     Covers <see cref="ProbeCommand.ComputeVerdict"/> — the headline-string helper that
///     combines the driver-side <see cref="DriverState"/> with the probe snapshot's OPC UA
///     <see cref="DataValueSnapshot.StatusCode"/> so the operator never sees the previous
///     contradictory pair (`Health: Healthy` above a `Status: Bad...` snapshot line — see
///     Driver.Modbus.Cli-006).
/// </summary>
[Trait("Category", "Unit")]
public sealed class ProbeCommandTests
{
    /// <summary>Verifies that ComputeVerdict returns OK when driver state is Healthy and status is Good.</summary>
    [Fact]
    public void ComputeVerdict_returns_OK_when_state_is_Healthy_and_status_is_Good()
    {
        var verdict = ProbeCommand.ComputeVerdict(DriverState.Healthy, statusCode: 0x00000000u);

        verdict.ShouldContain("OK");
    }

    /// <summary>Verifies that ComputeVerdict returns FAIL when driver state is not Healthy.</summary>
    /// <param name="state">The driver state to test.</param>
    [Theory]
    [InlineData(DriverState.Faulted)]
    [InlineData(DriverState.Reconnecting)]
    [InlineData(DriverState.Unknown)]
    public void ComputeVerdict_returns_FAIL_when_driver_state_is_not_Healthy(DriverState state)
    {
        var verdict = ProbeCommand.ComputeVerdict(state, statusCode: 0x00000000u);

        verdict.ShouldContain("FAIL");
    }

    /// <summary>Verifies that ComputeVerdict returns FAIL when snapshot status is Bad even if driver is Healthy.</summary>
    /// <param name="statusCode">The OPC UA status code to test.</param>
    [Theory]
    [InlineData(0x80050000u)] // BadCommunicationError
    [InlineData(0x800A0000u)] // BadTimeout
    [InlineData(0x80740000u)] // BadTypeMismatch
    [InlineData(0x80000000u)] // generic Bad
    public void ComputeVerdict_returns_FAIL_when_snapshot_status_is_Bad_even_if_driver_state_Healthy(uint statusCode)
    {
        // Driver.Modbus.Cli-006: a successful InitializeAsync sets DriverState.Healthy, but
        // the FC03 probe read may still fail (snapshot.StatusCode != Good). Previously the
        // headline reported Healthy while the snapshot line below showed Bad. The verdict
        // must reflect the actual probe-read outcome.
        var verdict = ProbeCommand.ComputeVerdict(DriverState.Healthy, statusCode);

        verdict.ShouldContain("FAIL");
    }

    /// <summary>Verifies that ComputeVerdict returns DEGRADED for uncertain status with healthy driver.</summary>
    [Fact]
    public void ComputeVerdict_returns_DEGRADED_for_uncertain_status_with_healthy_driver()
    {
        var verdict = ProbeCommand.ComputeVerdict(DriverState.Healthy, statusCode: 0x40000000u);

        verdict.ShouldContain("DEGRADED");
    }
}
