using System.Text.Json;

namespace Baya.Application.Common;

/// <summary>
/// Shared (de)serialization for a small list of stable string codes persisted as a JSON string array
/// (e.g. patient <c>conditions_json</c>, nurse <c>specializations_json</c>). A malformed or empty value
/// parses to an empty list; an empty list serializes back to <c>null</c> (a clean NULL column).
/// </summary>
public static class JsonCodeList
{
    public static IReadOnlyList<string> Parse(string json)
    {
        if (string.IsNullOrWhiteSpace(json))
            return [];

        try
        {
            return JsonSerializer.Deserialize<List<string>>(json) ?? [];
        }
        catch (JsonException)
        {
            return [];
        }
    }

    public static string Serialize(IReadOnlyList<string> codes)
        => codes is null || codes.Count == 0 ? null : JsonSerializer.Serialize(codes);
}
