using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StellaOps.Plugin;

namespace StellaOps.Excititor.Worker.Scheduling;

internal sealed class DefaultVexProviderRunner : IVexProviderRunner
{
    private readonly IServiceProvider _serviceProvider;
    private readonly PluginCatalog _pluginCatalog;
    private readonly ILogger<DefaultVexProviderRunner> _logger;

    public DefaultVexProviderRunner(
        IServiceProvider serviceProvider,
        PluginCatalog pluginCatalog,
        ILogger<DefaultVexProviderRunner> logger)
    {
        _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
        _pluginCatalog = pluginCatalog ?? throw new ArgumentNullException(nameof(pluginCatalog));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public ValueTask RunAsync(string providerId, CancellationToken cancellationToken)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(providerId);

        using var scope = _serviceProvider.CreateScope();
        var availablePlugins = _pluginCatalog.GetAvailableConnectorPlugins(scope.ServiceProvider);
        var matched = availablePlugins.FirstOrDefault(plugin =>
            string.Equals(plugin.Name, providerId, StringComparison.OrdinalIgnoreCase));

        if (matched is null)
        {
            _logger.LogInformation("No connector plugin registered for provider {ProviderId}; nothing to execute.", providerId);
            return ValueTask.CompletedTask;
        }

        _logger.LogInformation(
            "Connector plugin {PluginName} ({ProviderId}) is available. Execution hooks will be added in subsequent tasks.",
            matched.Name,
            providerId);

        return ValueTask.CompletedTask;
    }
}
