using System.Linq;
using MongoDB.Driver;
using StellaOps.Scanner.Storage.Catalog;

namespace StellaOps.Scanner.Storage.Migrations;

public sealed class EnsureLifecycleRuleTtlMigration : IMongoMigration
{
    public string Id => "20251018-lifecycle-ttl";

    public string Description => "Ensure lifecycle_rules expiresAt TTL index exists.";

    public async Task ApplyAsync(IMongoDatabase database, CancellationToken cancellationToken)
    {
        var collection = database.GetCollection<LifecycleRuleDocument>(ScannerStorageDefaults.Collections.LifecycleRules);
        var indexes = await collection.Indexes.ListAsync(cancellationToken).ConfigureAwait(false);
        var existing = await indexes.ToListAsync(cancellationToken).ConfigureAwait(false);

        if (existing.Any(x => string.Equals(x["name"].AsString, "lifecycle_expiresAt", StringComparison.Ordinal)))
        {
            return;
        }

        var model = new CreateIndexModel<LifecycleRuleDocument>(
            Builders<LifecycleRuleDocument>.IndexKeys.Ascending(x => x.ExpiresAtUtc),
            new CreateIndexOptions { Name = "lifecycle_expiresAt", ExpireAfter = TimeSpan.Zero });

        await collection.Indexes.CreateOneAsync(model, cancellationToken: cancellationToken).ConfigureAwait(false);
    }
}
