using System.Text.Json;
using TakeoutSaaS.Domain.Dictionary.ValueObjects;

namespace TakeoutSaaS.Application.Dictionary.Services;

/// <summary>
/// 字典值序列化与反序列化辅助。
/// </summary>
internal static class DictionaryValueConverter
{
    /// <summary>
    /// 将多语言字典序列化为 JSON。
    /// </summary>
    public static string Serialize(Dictionary<string, string> values)
    {
        var i18n = new I18nValue(values);
        return i18n.ToJson();
    }

    /// <summary>
    /// 将 JSON 解析为多语言字典。
    /// </summary>
    public static Dictionary<string, string> Deserialize(string? json)
    {
        if (string.IsNullOrWhiteSpace(json))
        {
            return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }

        try
        {
            return I18nValue.FromJson(json).ToDictionary();
        }
        catch (JsonException)
        {
            return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
            {
                ["zh-CN"] = json.Trim()
            };
        }
        catch (ArgumentException)
        {
            return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }
    }
}
