using System.Net.Http.Headers;

namespace OpenWarehouse.auth.lib;

public class AuthTokenHandler : DelegatingHandler
{
    private string _token;

    public AuthTokenHandler(string token) 
    {
        _token = token;
        InnerHandler = new HttpClientHandler();
    }
    
    public void UpdateToken(string newToken)
    {
        _token = newToken;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (!string.IsNullOrEmpty(_token))
        {
            if (_token.Contains(" "))
            {
                var tokenSplit = _token.Split(" ");
                request.Headers.Authorization = new AuthenticationHeaderValue(tokenSplit[0], tokenSplit[1]);
            }
            else
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _token);
            }
        }

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