using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Helpers
{
    public static class DHHeaderUtil
    {
        public static Dictionary<string, string> BuildHeader(
        string ak,
        string sk,
        string httpMethod,
        string canonicalizedResource)
        {
            // 1. UTC 时间格式化
            string utcDate = DateTime.UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'");
            //string utcDate = "20250813T085311Z";
            Console.WriteLine("UTC时间: " + utcDate);
            // 2. 拼接签名字符串 
            string stringToSign = $"{httpMethod}\n\napplication/json\n{utcDate}\n" +
                         $"x-lc-date:{utcDate}\n" +
                         "x-lc-version:1.0\n" +
                         $"{canonicalizedResource}";
            Console.WriteLine("StringToSign: " + stringToSign);

            // 3. 生成 HMAC-SHA256
            string signature;
            using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(sk)))
            {
                var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
                signature = Convert.ToBase64String(hashBytes);
            }

            Console.WriteLine("HmacSHA256+Base64: " + signature);

            // 4. Authorization
            string authorization = $"LC-HMAC-SHA256 {ak}:{signature}";
            Console.WriteLine("Authorization: " + authorization);

            // 5. 返回请求头字典
            return new Dictionary<string, string>
            { 
                { "Authorization", authorization },
                { "X-LC-Date", utcDate },
                { "X-LC-Version", "1.0" }
            };
        }

        /// <summary>
        /// 生成 HMAC-SHA256 签名，并 Base64 编码
        /// </summary>
        public static string Sign(string stringToSign, string key)
        {
            if (string.IsNullOrEmpty(stringToSign) || string.IsNullOrEmpty(key))
                return null;

            using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
            byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            return Convert.ToBase64String(hashBytes);
        }
    }
}
