using Microsoft.Graph;
using Microsoft.Identity.Client;
using Microsoft.Kiota.Abstractions.Authentication;

namespace SharepointToolbox.Infrastructure.Auth;

public class GraphClientFactory
{
    private readonly MsalClientFactory _msalFactory;

    public GraphClientFactory(MsalClientFactory msalFactory)
    {
        _msalFactory = msalFactory;
    }

    /// <summary>
    /// Creates a GraphServiceClient that acquires tokens via the same MSAL PCA
    /// used for SharePoint auth, but with Graph scopes.
    /// </summary>
    public async Task<GraphServiceClient> CreateClientAsync(string clientId, CancellationToken ct)
    {
        var pca = await _msalFactory.GetOrCreateAsync(clientId);
        var accounts = await pca.GetAccountsAsync();
        var account = accounts.FirstOrDefault();

        var graphScopes = new[] { "https://graph.microsoft.com/.default" };

        var tokenProvider = new MsalTokenProvider(pca, account, graphScopes);
        var authProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
        return new GraphServiceClient(authProvider);
    }
}

/// <summary>
/// Bridges MSAL PCA token acquisition with Graph SDK's IAccessTokenProvider interface.
/// </summary>
internal class MsalTokenProvider : IAccessTokenProvider
{
    private readonly IPublicClientApplication _pca;
    private readonly IAccount? _account;
    private readonly string[] _scopes;

    public MsalTokenProvider(IPublicClientApplication pca, IAccount? account, string[] scopes)
    {
        _pca = pca;
        _account = account;
        _scopes = scopes;
    }

    public AllowedHostsValidator AllowedHostsValidator { get; } = new();

    public async Task<string> GetAuthorizationTokenAsync(
        Uri uri,
        Dictionary<string, object>? additionalAuthenticationContext = null,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var result = await _pca.AcquireTokenSilent(_scopes, _account)
                .ExecuteAsync(cancellationToken);
            return result.AccessToken;
        }
        catch (MsalUiRequiredException)
        {
            // If silent fails, try interactive
            var result = await _pca.AcquireTokenInteractive(_scopes)
                .ExecuteAsync(cancellationToken);
            return result.AccessToken;
        }
    }
}
