using System.Net.Http.Json;
using Lentia.Core.Constants;

namespace Lentia.Core.Utils;

public static class HttpHelper {

    private static readonly HttpClient Http = new HttpClient();

    public static async Task<HttpResponseMessage> FetchAsync(string url, HttpMethod? method = null, object? body = null, Dictionary<string, string>? headers = null) {
        var request = new HttpRequestMessage(method ?? HttpMethod.Get, url);

        if (headers != null) {
            foreach (var header in headers) {
                request.Headers.TryAddWithoutValidation(header.Key, header.Value);
            }
        }

        if (body != null) {
            if (body is HttpContent httpContent) {
                request.Content = httpContent;
            } else if (body is string s) {
                request.Content = new StringContent(s, System.Text.Encoding.UTF8, "application/json");
            } else {
                request.Content = JsonContent.Create(body, options: LauncherConstants._jsonOptions);
            }
        }

        request.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64)");

        return await Http.SendAsync(request);
    }

}