using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace ZB.MOM.WW.Secrets.Replicator.SqlServer;

/// <summary>
/// Provisions the shared hub schema at startup in hub-replication mode.
/// </summary>
/// <remarks>
/// Separate from the core migration hosted service on purpose: in hub mode there are <em>two</em>
/// stores to provision — the node's local one (handled by the core service through the
/// <c>ISecretsStoreMigrator</c> seam) and the shared hub, which no node "owns". Every node runs this
/// idempotently at startup, so the hub exists as soon as any node has started, with no separate
/// provisioning step for an operator to forget.
/// </remarks>
/// <param name="migrator">The hub migrator.</param>
/// <param name="options">Core secrets options, for the shared startup-migration switch.</param>
internal sealed class SqlServerHubMigrationHostedService(
    SqlServerSecretsStoreMigrator 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;
}
