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 => HistorianStatusCodes.Good,
        216 => HistorianStatusCodes.GoodLocalOverride,

        // Uncertain family (64-191)
        64 => HistorianStatusCodes.Uncertain,
        68 => HistorianStatusCodes.UncertainLastUsableValue,
        80 => HistorianStatusCodes.UncertainSensorNotAccurate,
        84 => HistorianStatusCodes.UncertainEngineeringUnitsExceeded,
        88 => HistorianStatusCodes.UncertainSubNormal,

        // Bad family (0-63)
        0 => HistorianStatusCodes.Bad,
        4 => HistorianStatusCodes.BadConfigurationError,
        8 => HistorianStatusCodes.BadNotConnected,
        12 => HistorianStatusCodes.BadDeviceFailure,
        16 => HistorianStatusCodes.BadSensorFailure,
        20 => HistorianStatusCodes.BadCommunicationError,
        24 => HistorianStatusCodes.BadOutOfService,
        32 => HistorianStatusCodes.BadWaitingForInitialData,

        // Unknown — fall back to category bucket so callers still get something usable.
        _ when q >= 192 => HistorianStatusCodes.Good,
        _ when q >= 64 => HistorianStatusCodes.Uncertain,
        _ => HistorianStatusCodes.Bad,
    };
}
