using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Secrets.Abstractions;

namespace ZB.MOM.WW.Secrets.DependencyInjection;

/// <summary>
/// Runs the secret-store schema migration at application startup when
/// <see cref="SecretsOptions.RunMigrationsOnStartup"/> is <see langword="true"/>. The migration is
/// idempotent, so repeated restarts are safe.
/// </summary>
/// <remarks>
/// Depends on the <see cref="ISecretsStoreMigrator"/> seam rather than a concrete migrator, so the
/// same hosted service provisions the local SQLite store or the shared SQL-Server store depending
/// only on which migrator the application registered.
/// </remarks>
internal sealed class SecretsMigrationHostedService(
    ISecretsStoreMigrator migrator,
    IOptions<SecretsOptions> options) : IHostedService
{
    /// <inheritdoc />
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (options.Value.RunMigrationsOnStartup)
        {
            await migrator.MigrateAsync(cancellationToken).ConfigureAwait(false);
        }
    }

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