using System.Security.Cryptography;
using System.Text;

namespace XPrintServer.Api.Tools
{
    public class HashTool
    {
        /// <summary>
        /// 获取请求体的 SHA256 哈希值
        /// </summary>
        /// <param name="body">请求体内容</param>
        /// <returns>SHA256 哈希值的十六进制字符串</returns>
        public static string GetBodySha256(object body)
        {
            using (var sha256 = SHA256.Create())
            {
                byte[] bytesToHash = GetBytesFromBody(body);
                byte[] hashBytes = sha256.ComputeHash(bytesToHash);
                return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
            }
        }

        /// <summary>
        /// 根据不同类型获取字节数组
        /// </summary>
        private static byte[] GetBytesFromBody(object body)
        {
            if (body == null)
            {
                return Array.Empty<byte>();
            }

            switch (body)
            {
                case string strBody:
                    return Encoding.UTF8.GetBytes(strBody);

                case byte[] byteArrayBody:
                    return byteArrayBody;

                case System.Collections.Specialized.NameValueCollection formData:
                    // 处理类似 URLSearchParams 的键值对集合
                    var sb = new StringBuilder();
                    foreach (string key in formData.AllKeys)
                    {
                        if (sb.Length > 0)
                            sb.Append('&');

                        sb.Append(Uri.EscapeDataString(key))
                          .Append('=')
                          .Append(Uri.EscapeDataString(formData[key]));
                    }
                    return Encoding.UTF8.GetBytes(sb.ToString());

                case System.Collections.Generic.IDictionary<string, string> dictionary:
                    // 处理字典类型的键值对
                    var dictSb = new StringBuilder();
                    foreach (var kvp in dictionary)
                    {
                        if (dictSb.Length > 0)
                            dictSb.Append('&');

                        dictSb.Append(Uri.EscapeDataString(kvp.Key))
                             .Append('=')
                             .Append(Uri.EscapeDataString(kvp.Value));
                    }
                    return Encoding.UTF8.GetBytes(dictSb.ToString());

                default:
                    // 其他类型尝试转换为字符串
                    return Encoding.UTF8.GetBytes(body.ToString());
            }
        }
    }
}
