namespace JSMR.Infrastructure.Http;

public class HttpService(HttpClient httpClient) : IHttpService
{
    public Task<HttpStringResponse> GetAsync(string url, CancellationToken cancellationToken)
        => GetAsync(url, new Dictionary<string, string>(), cancellationToken);

    public async Task<HttpStringResponse> GetAsync(string url, IDictionary<string, string> headers, CancellationToken cancellationToken)
    {
        using HttpRequestMessage request = new(HttpMethod.Get, url);

        foreach (KeyValuePair<string, string> header in headers)
        {
            request.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }

        request.Headers.UserAgent.ParseAdd("JSMR/1.0");

        using HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);

        string? content = response.Content is null
            ? null
            : await response.Content.ReadAsStringAsync(cancellationToken);

        return new HttpStringResponse
        {
            StatusCode = response.StatusCode,
            Content = content
        };
    }
}