using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using System.Net.Http.Headers;

namespace RobotNet.WebApp.Helpers;

public static class ServiceCollectionExtensions
{
    public static IHttpClientBuilder AddAuthorizationHttpClient(this IServiceCollection services, string name, string baseAddress)
    {
        return services.AddHttpClient(name, client =>
        {
            client.BaseAddress = new Uri(baseAddress);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        })
        .AddHttpMessageHandler(sp =>
        {
            var tokenProvider = sp.GetRequiredService<IAccessTokenProvider>();
            var navigation = sp.GetRequiredService<NavigationManager>();
            var messageHandle = new AuthorizationMessageHandler(tokenProvider, navigation);

            messageHandle.ConfigureHandler([baseAddress]);
            return messageHandle;
        })
        .RemoveAllLoggers();
    }
}
