using OpenIddict.Client;
using RobotNet.OpenIddictClient;
using System.Net.Http.Headers;

namespace RobotNet.RobotManager.Services;

public class MapManagerAccessTokenHandler(OpenIddictClientService openIddictClient, IConfiguration configuration) : DelegatingHandler
{
    private readonly OpenIddictResourceOptions options = configuration.GetSection("MapManager").Get<OpenIddictResourceOptions>() ?? throw new InvalidOperationException("OpenID configuration not found or invalid format.");
    private string? CachedToken;
    private DateTime TokenExpiry;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (string.IsNullOrEmpty(CachedToken) || DateTime.UtcNow >= TokenExpiry)
        {
            var result = await openIddictClient.AuthenticateWithClientCredentialsAsync(new()
            {
                Scopes = [.. options.Scopes],
            });

            if (result != null && !string.IsNullOrEmpty(result.AccessToken) && result.AccessTokenExpirationDate != null)
            {
                TokenExpiry = result.AccessTokenExpirationDate.Value.UtcDateTime;
                CachedToken = result.AccessToken;
            }
        }

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", CachedToken);

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