using Microsoft.AspNetCore.Components;
using System.Net;
using System.Net.Http.Headers;
using TechHelper.Client.HttpRepository;


namespace BlazorProducts.Client.HttpInterceptor
{
	public class HttpInterceptorHandlerService : DelegatingHandler
	{
		private readonly NavigationManager _navManager;
		private readonly IRefreshTokenService _refreshTokenService;

		public HttpInterceptorHandlerService(
			NavigationManager navManager,
			IRefreshTokenService refreshTokenService)
		{
			_navManager = navManager;
			_refreshTokenService = refreshTokenService;
		}

		protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			var absolutePath = request.RequestUri?.AbsolutePath;

			if (absolutePath != null && !absolutePath.Contains("token") && !absolutePath.Contains("account"))
			{
				var token = await _refreshTokenService.TryRefreshToken();
				if (!string.IsNullOrEmpty(token))
				{
					request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
				}
			}


			var response = await base.SendAsync(request, cancellationToken);

			await HandleResponse(response);

			return response;
		}

		private async Task HandleResponse(HttpResponseMessage response)
		{
			if (response is null)
			{

				_navManager.NavigateTo("/error");
				throw new HttpResponseException("服务器不可用。");
			}


			if (!response.IsSuccessStatusCode)
			{

				var errorContent = await response.Content.ReadAsStringAsync();
				Console.WriteLine($"HTTP 错误: {response.StatusCode}. 详情: {errorContent}");

				switch (response.StatusCode)
				{
					case HttpStatusCode.NotFound:
						// 404 Not Found error, navigate to a 404 page.
						_navManager.NavigateTo("/404");
						break;
					case HttpStatusCode.BadRequest:
						// 400 Bad Request error. Often, you don't navigate for this; you display validation errors on the UI.
						break;
					case HttpStatusCode.Unauthorized:
						var token = await _refreshTokenService.TryRefreshToken();
						if (!string.IsNullOrEmpty(token))
						{
							_navManager.NavigateTo(_navManager.Uri, forceLoad: true);
						}
						else
						{
							_navManager.NavigateTo("/unauthorized");
						}
						break;
					default:
						// For all other errors, navigate to a general error page.
						_navManager.NavigateTo("/error");
						break;
				}
			}
		}
	}

}