using System.Text.Json;

namespace Meezi.Core.Authorization;

/// <summary>Helpers for serialising/deserialising a custom role's permission set.</summary>
public static class CustomRolePermissions
{
    private static readonly JsonSerializerOptions JsonOpts = new(JsonSerializerDefaults.Web);

    /// <summary>Parse the stored JSON array of permission names into a set.</summary>
    public static IReadOnlySet<Permission> Parse(string? json)
    {
        if (string.IsNullOrWhiteSpace(json)) return new HashSet<Permission>();
        try
        {
            var names = JsonSerializer.Deserialize<string[]>(json, JsonOpts) ?? [];
            var set = new HashSet<Permission>();
            foreach (var name in names)
                if (Enum.TryParse<Permission>(name, ignoreCase: true, out var p))
                    set.Add(p);
            return set;
        }
        catch
        {
            return new HashSet<Permission>();
        }
    }

    /// <summary>Serialise a permission set to JSON for storage.</summary>
    public static string Serialize(IEnumerable<Permission> permissions) =>
        JsonSerializer.Serialize(permissions.Select(p => p.ToString()).ToArray(), JsonOpts);
}
