using System.Text.Json;
using Meezi.Core.Discover;

namespace Meezi.Infrastructure.Discover;

public static class DiscoverBadgesSerializer
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public static IReadOnlyList<string> Deserialize(string? json)
    {
        if (string.IsNullOrWhiteSpace(json)) return [];
        try
        {
            var list = JsonSerializer.Deserialize<List<string>>(json, JsonOptions);
            return CafeBadgeCatalog.NormalizeKeys(list);
        }
        catch
        {
            return [];
        }
    }

    public static string? Serialize(IEnumerable<string>? keys)
    {
        var normalized = CafeBadgeCatalog.NormalizeKeys(keys);
        return normalized.Count == 0 ? null : JsonSerializer.Serialize(normalized, JsonOptions);
    }
}
