using MilkStream.Services;
using System.Net;

namespace MilkStream;

/// <summary>
/// Can be added to an HTTP client to automatically refresh JWT tokens when they expire.
/// </summary>
/// <param name="loginService">login service that handles the current identity</param>
public class JwtTokenRefresher(LoginService loginService) : DelegatingHandler {
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        //pass through the current request and get the response
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        //if the response is not unauthorized or the login service has no auth info, return the response
        if (response.StatusCode != HttpStatusCode.Unauthorized || loginService.authInfo == null) return response;
        //if we got a 401 Unauthorized, we need to reauthenticate
        await loginService.Reauthenticate().ConfigureAwait(false);
        //if reauthentication was successful, resend the request with the new token
        request.Headers.Authorization = new ("bearer", loginService.authInfo.Token);
        response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        //whatever is the response this time, return it
        return response;
    }
}
