using Newtonsoft.Json;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HuanMeng.DotNetCore.Utility;

/// <summary>
/// 
/// </summary>
public static class HttpResponseMessageExtensions
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="response"></param>
    /// <returns></returns>
    public static async Task<string> ToJsonAsync(this HttpResponseMessage response)
    {
        var responseInfo = new
        {
            StatusCode = response.StatusCode,
            ReasonPhrase = response.ReasonPhrase,
            Headers = response.Headers,
            Content = response.Content != null ? await response.Content.ReadAsStringAsync() : null,
            RequestMessage = response.RequestMessage != null
                ? new
                {
                    Method = response.RequestMessage.Method.Method,
                    Url = response.RequestMessage.RequestUri.ToString()
                }
                : null
        };

        return JsonConvert.SerializeObject(responseInfo, Formatting.Indented);
    }
}
