using System.Text.RegularExpressions;

namespace TakeoutSaaS.Application.App.Products;

/// <summary>
/// 商品标签映射辅助。
/// </summary>
internal static partial class ProductLabelMapping
{
    /// <summary>
    /// 解析状态字符串。
    /// </summary>
    public static bool TryParseStatus(string? status, out bool isEnabled)
    {
        var normalized = status?.Trim().ToLowerInvariant();
        switch (normalized)
        {
            case "enabled":
                isEnabled = true;
                return true;
            case "disabled":
                isEnabled = false;
                return true;
            default:
                isEnabled = true;
                return false;
        }
    }

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

    /// <summary>
    /// 归一化颜色值。
    /// </summary>
    public static bool TryNormalizeColor(string? color, out string normalized)
    {
        var candidate = (color ?? string.Empty).Trim().ToLowerInvariant();
        if (string.IsNullOrWhiteSpace(candidate))
        {
            normalized = "#1890ff";
            return true;
        }

        if (!candidate.StartsWith('#'))
        {
            candidate = $"#{candidate}";
        }

        if (ShortHexColorRegex().IsMatch(candidate))
        {
            normalized = $"#{candidate[1]}{candidate[1]}{candidate[2]}{candidate[2]}{candidate[3]}{candidate[3]}";
            return true;
        }

        if (LongHexColorRegex().IsMatch(candidate))
        {
            normalized = candidate;
            return true;
        }

        normalized = "#1890ff";
        return false;
    }

    [GeneratedRegex("^#[0-9a-f]{3}$", RegexOptions.Compiled)]
    private static partial Regex ShortHexColorRegex();

    [GeneratedRegex("^#[0-9a-f]{6}$", RegexOptions.Compiled)]
    private static partial Regex LongHexColorRegex();
}
