using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Blazored.LocalStorage;

namespace DiplomovaPrace.Web.Admin.Infrastructure
{
	public class AuthorizationHeaderHandler : DelegatingHandler
	{
		private readonly ILocalStorageService localStorageService;

		public AuthorizationHeaderHandler(ILocalStorageService localStorageService)
		{
			this.localStorageService = localStorageService;
		}

		protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (request.Headers.Authorization is null)
			{
				string token = await localStorageService.GetItemAsync<string>(nameof(LocalStorageType.AuthorizationToken)).ConfigureAwait(false);

				if (!string.IsNullOrWhiteSpace(token))
				{
					request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
				}
			}

			return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
		}
	}
}
