using Microsoft.Extensions.Logging; using MongoDB.Driver; using StellaOps.Scheduler.Storage.Mongo.Internal; namespace StellaOps.Scheduler.Storage.Mongo.Migrations; internal sealed class EnsureSchedulerCollectionsMigration : ISchedulerMongoMigration { private readonly ILogger _logger; public EnsureSchedulerCollectionsMigration(ILogger logger) => _logger = logger ?? throw new ArgumentNullException(nameof(logger)); public string Id => "20251019_scheduler_collections_v1"; public async ValueTask ExecuteAsync(SchedulerMongoContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); var requiredCollections = new[] { context.Options.SchedulesCollection, context.Options.RunsCollection, context.Options.ImpactSnapshotsCollection, context.Options.AuditCollection, context.Options.LocksCollection, context.Options.MigrationsCollection }; var cursor = await context.Database .ListCollectionNamesAsync(cancellationToken: cancellationToken) .ConfigureAwait(false); var existing = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); foreach (var collection in requiredCollections) { if (existing.Contains(collection, StringComparer.Ordinal)) { continue; } _logger.LogInformation("Creating Scheduler Mongo collection '{CollectionName}'.", collection); await context.Database.CreateCollectionAsync(collection, cancellationToken: cancellationToken).ConfigureAwait(false); } } }