using System.Text.Json;

namespace TakeoutSaaS.Application.App.Products;

/// <summary>
/// 分类管理映射辅助。
/// </summary>
internal static class ProductCategoryManageMapping
{
    private static readonly string[] ChannelOrder = ["wm", "pickup", "dine_in"];
    private static readonly HashSet<string> AllowedChannels = [.. ChannelOrder];

    /// <summary>
    /// 解析状态字符串。
    /// </summary>
    public static bool TryParseStatus(string? status, out bool isEnabled)
    {
        var normalized = NormalizeStatus(status);
        if (normalized is null)
        {
            isEnabled = true;
            return false;
        }

        isEnabled = normalized == "enabled";
        return true;
    }

    /// <summary>
    /// 状态转字符串。
    /// </summary>
    public static string ToStatusText(bool isEnabled)
    {
        return isEnabled ? "enabled" : "disabled";
    }

    /// <summary>
    /// 渠道集合标准化。
    /// </summary>
    public static List<string> NormalizeChannels(IEnumerable<string>? channels)
    {
        var normalized = new HashSet<string>(
            (channels ?? [])
            .Select(channel => channel?.Trim().ToLowerInvariant() ?? string.Empty)
            .Where(channel => AllowedChannels.Contains(channel)));

        return ChannelOrder
            .Where(normalized.Contains)
            .ToList();
    }

    /// <summary>
    /// 渠道集合序列化。
    /// </summary>
    public static string SerializeChannels(IEnumerable<string>? channels)
    {
        var normalized = NormalizeChannels(channels);
        if (normalized.Count == 0)
        {
            normalized = ["wm"];
        }

        return JsonSerializer.Serialize(normalized);
    }

    /// <summary>
    /// 渠道集合反序列化。
    /// </summary>
    public static List<string> DeserializeChannels(string? channelsJson)
    {
        if (string.IsNullOrWhiteSpace(channelsJson))
        {
            return ["wm"];
        }

        try
        {
            var parsed = JsonSerializer.Deserialize<List<string>>(channelsJson);
            var normalized = NormalizeChannels(parsed);
            return normalized.Count > 0 ? normalized : ["wm"];
        }
        catch
        {
            return ["wm"];
        }
    }

    /// <summary>
    /// 判断状态值是否合法。
    /// </summary>
    public static bool IsValidStatus(string? status)
    {
        return NormalizeStatus(status) is not null;
    }

    /// <summary>
    /// 判断渠道值是否合法。
    /// </summary>
    public static bool IsValidChannel(string? channel)
    {
        if (string.IsNullOrWhiteSpace(channel))
        {
            return false;
        }

        return AllowedChannels.Contains(channel.Trim().ToLowerInvariant());
    }

    private static string? NormalizeStatus(string? status)
    {
        var normalized = status?.Trim().ToLowerInvariant();
        return normalized is "enabled" or "disabled" ? normalized : null;
    }
}
