using System;
using System.Collections.Generic;
using MongoDB.Driver;
using StellaOps.Authority.Storage.Mongo.Documents;

namespace StellaOps.Authority.Storage.Mongo.Initialization;

internal sealed class AuthorityRevocationCollectionInitializer : IAuthorityCollectionInitializer
{
    public async ValueTask EnsureIndexesAsync(IMongoDatabase database, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(database);

        var collection = database.GetCollection<AuthorityRevocationDocument>(AuthorityMongoDefaults.Collections.Revocations);
        var indexModels = new List<CreateIndexModel<AuthorityRevocationDocument>>
        {
            new(
                Builders<AuthorityRevocationDocument>.IndexKeys
                    .Ascending(d => d.Category)
                    .Ascending(d => d.RevocationId),
                new CreateIndexOptions<AuthorityRevocationDocument> { Name = "revocation_identity_unique", Unique = true }),
            new(
                Builders<AuthorityRevocationDocument>.IndexKeys.Ascending(d => d.RevokedAt),
                new CreateIndexOptions<AuthorityRevocationDocument> { Name = "revocation_revokedAt" }),
            new(
                Builders<AuthorityRevocationDocument>.IndexKeys.Ascending(d => d.ExpiresAt),
                new CreateIndexOptions<AuthorityRevocationDocument> { Name = "revocation_expiresAt" })
        };

        await collection.Indexes.CreateManyAsync(indexModels, cancellationToken).ConfigureAwait(false);
    }
}
