namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Mapping;

/// <summary>
/// Maps a raw OPC DA quality byte (the gateway's <c>opc_quality</c> field) to an OPC UA StatusCode
/// uint.
/// </summary>
/// <remarks>
/// Byte-identical port of the historical Wonderware client's <c>QualityMapper.Map</c> (itself a
/// port of the original historian sidecar's <c>HistorianQualityMapper.Map</c>). Those projects have
/// since been retired; this is now the canonical quality table. Parity with the OPC DA quality
/// semantics is pinned by the per-byte tests.
/// </remarks>
internal static class GatewayQualityMapper
{
    /// <summary>Maps an OPC DA quality byte to an OPC UA StatusCode.</summary>
    /// <param name="q">The OPC DA quality byte value.</param>
    /// <returns>An OPC UA StatusCode as a uint.</returns>
    public static uint Map(byte q) => q switch
    {
        // Good family (192+)
        192 => 0x00000000u,             // Good
        216 => 0x00D80000u,             // Good_LocalOverride

        // Uncertain family (64-191)
        64 => 0x40000000u,              // Uncertain
        68 => 0x40900000u,              // Uncertain_LastUsableValue
        80 => 0x40930000u,              // Uncertain_SensorNotAccurate
        84 => 0x40940000u,              // Uncertain_EngineeringUnitsExceeded
        88 => 0x40950000u,              // Uncertain_SubNormal

        // Bad family (0-63)
        0 => 0x80000000u,               // Bad
        4 => 0x80890000u,               // Bad_ConfigurationError
        8 => 0x808A0000u,               // Bad_NotConnected
        12 => 0x808B0000u,              // Bad_DeviceFailure
        16 => 0x808C0000u,              // Bad_SensorFailure
        20 => 0x80050000u,              // Bad_CommunicationError
        24 => 0x808D0000u,              // Bad_OutOfService
        32 => 0x80320000u,              // Bad_WaitingForInitialData

        // Unknown — fall back to category bucket so callers still get something usable.
        _ when q >= 192 => 0x00000000u,
        _ when q >= 64 => 0x40000000u,
        _ => 0x80000000u,
    };
}
