using MongoDB.Driver;
using StellaOps.Authority.Storage.Mongo.Documents;

namespace StellaOps.Authority.Storage.Mongo.Initialization;

internal sealed class AuthorityLoginAttemptCollectionInitializer : IAuthorityCollectionInitializer
{
    public async ValueTask EnsureIndexesAsync(IMongoDatabase database, CancellationToken cancellationToken)
    {
        var collection = database.GetCollection<AuthorityLoginAttemptDocument>(AuthorityMongoDefaults.Collections.LoginAttempts);

        var indexModels = new[]
        {
            new CreateIndexModel<AuthorityLoginAttemptDocument>(
                Builders<AuthorityLoginAttemptDocument>.IndexKeys
                    .Ascending(a => a.SubjectId)
                    .Descending(a => a.OccurredAt),
                new CreateIndexOptions { Name = "login_attempt_subject_time" }),
            new CreateIndexModel<AuthorityLoginAttemptDocument>(
                Builders<AuthorityLoginAttemptDocument>.IndexKeys.Descending(a => a.OccurredAt),
                new CreateIndexOptions { Name = "login_attempt_time" }),
            new CreateIndexModel<AuthorityLoginAttemptDocument>(
                Builders<AuthorityLoginAttemptDocument>.IndexKeys
                    .Ascending(a => a.CorrelationId),
                new CreateIndexOptions { Name = "login_attempt_correlation", Sparse = true })
        };

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