using System.Net.Http.Json;
using BrikInstaller;

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) {
        Console.WriteLine($"Fetching {url} using {method} method");
        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: Constants._jsonOptions);
            }
        }

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

        return await Http.SendAsync(request);
    }

    public static async Task DownloadFileAsync(string url, string destinationPath) {
        Console.WriteLine($"Downloading file from {url} to {destinationPath}");
        string? directory = Path.GetDirectoryName(destinationPath);
        if (!string.IsNullOrEmpty(directory)) {
            Directory.CreateDirectory(directory);
        }

        if (File.Exists(destinationPath)) {
            File.Delete(destinationPath);
        }

        using var response = await HttpHelper.FetchAsync(url); 
        response.EnsureSuccessStatusCode();

        using var streamToReadFrom = await response.Content.ReadAsStreamAsync();
        using var streamToWriteTo = File.Create(destinationPath);
        
        await streamToReadFrom.CopyToAsync(streamToWriteTo);
    }
}