using System.Text.Json;

namespace ZB.MOM.WW.MxGateway.Server.Security.Authentication;

public static class ApiKeyScopeSerializer
{
    /// <summary>Serializes scopes to JSON string.</summary>
    /// <param name="scopes">The scopes to serialize.</param>
    /// <returns>JSON string representation.</returns>
    public static string Serialize(IReadOnlySet<string> scopes)
    {
        return JsonSerializer.Serialize(scopes.Order(StringComparer.Ordinal));
    }

    /// <summary>Deserializes scopes from JSON string.</summary>
    /// <param name="value">The JSON string to deserialize.</param>
    /// <returns>Deserialized scopes set.</returns>
    public static IReadOnlySet<string> Deserialize(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return new HashSet<string>(StringComparer.Ordinal);
        }

        string[]? scopes = JsonSerializer.Deserialize<string[]>(value);

        return new HashSet<string>(scopes ?? [], StringComparer.Ordinal);
    }
}
