using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;

namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;

/// <summary>
///     Maps between the library's SecurityMode enum and OPC UA SDK MessageSecurityMode.
/// </summary>
public static class SecurityModeMapper
{
    /// <summary>Converts a SecurityMode to an OPC UA MessageSecurityMode.</summary>
    /// <param name="mode">The security mode to convert.</param>
    /// <returns>The corresponding message security mode.</returns>
    public static MessageSecurityMode ToMessageSecurityMode(SecurityMode mode)
    {
        return mode switch
        {
            SecurityMode.None => MessageSecurityMode.None,
            SecurityMode.Sign => MessageSecurityMode.Sign,
            SecurityMode.SignAndEncrypt => MessageSecurityMode.SignAndEncrypt,
            _ => throw new ArgumentOutOfRangeException(nameof(mode), mode, "Unknown SecurityMode value.")
        };
    }

    /// <summary>
    ///     Parses a string to a <see cref="SecurityMode" /> value, case-insensitively.
    /// </summary>
    /// <param name="value">The string to parse (e.g., "none", "sign", "encrypt", "signandencrypt").</param>
    /// <returns>The corresponding SecurityMode.</returns>
    /// <exception cref="ArgumentException">Thrown for unrecognized values.</exception>
    public static SecurityMode FromString(string value)
    {
        return (value ?? "none").Trim().ToLowerInvariant() switch
        {
            "none" => SecurityMode.None,
            "sign" => SecurityMode.Sign,
            "encrypt" or "signandencrypt" => SecurityMode.SignAndEncrypt,
            _ => throw new ArgumentException(
                $"Unknown security mode '{value}'. Valid values: none, sign, encrypt, signandencrypt")
        };
    }
}