using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StellaOps.Authority.Plugin.Standard.Storage;

namespace StellaOps.Authority.Plugin.Standard.Bootstrap;

internal sealed class StandardPluginBootstrapper : IHostedService
{
    private readonly string pluginName;
    private readonly IOptionsMonitor<StandardPluginOptions> optionsMonitor;
    private readonly StandardUserCredentialStore credentialStore;
    private readonly ILogger<StandardPluginBootstrapper> logger;

    public StandardPluginBootstrapper(
        string pluginName,
        IOptionsMonitor<StandardPluginOptions> optionsMonitor,
        StandardUserCredentialStore credentialStore,
        ILogger<StandardPluginBootstrapper> logger)
    {
        this.pluginName = pluginName;
        this.optionsMonitor = optionsMonitor;
        this.credentialStore = credentialStore;
        this.logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var options = optionsMonitor.Get(pluginName);
        if (options.BootstrapUser is null || !options.BootstrapUser.IsConfigured)
        {
            return;
        }

        logger.LogInformation("Standard Authority plugin '{PluginName}' ensuring bootstrap user.", pluginName);
        await credentialStore.EnsureBootstrapUserAsync(options.BootstrapUser, cancellationToken).ConfigureAwait(false);
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
