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

namespace StellaOps.Authority.Storage.Mongo.Initialization;

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

        var indexModels = new[]
        {
            new CreateIndexModel<AuthorityUserDocument>(
                Builders<AuthorityUserDocument>.IndexKeys.Ascending(u => u.SubjectId),
                new CreateIndexOptions { Name = "user_subject_unique", Unique = true }),
            new CreateIndexModel<AuthorityUserDocument>(
                Builders<AuthorityUserDocument>.IndexKeys.Ascending(u => u.NormalizedUsername),
                new CreateIndexOptions { Name = "user_normalized_username_unique", Unique = true, Sparse = true }),
            new CreateIndexModel<AuthorityUserDocument>(
                Builders<AuthorityUserDocument>.IndexKeys.Ascending(u => u.Email),
                new CreateIndexOptions { Name = "user_email", Sparse = true })
        };

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