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

namespace StellaOps.Authority.Storage.Mongo.Initialization;

internal sealed class AuthorityBootstrapInviteCollectionInitializer : IAuthorityCollectionInitializer
{
    private static readonly CreateIndexModel<AuthorityBootstrapInviteDocument>[] Indexes =
    {
        new CreateIndexModel<AuthorityBootstrapInviteDocument>(
            Builders<AuthorityBootstrapInviteDocument>.IndexKeys.Ascending(i => i.Token),
            new CreateIndexOptions { Unique = true, Name = "idx_invite_token" }),
        new CreateIndexModel<AuthorityBootstrapInviteDocument>(
            Builders<AuthorityBootstrapInviteDocument>.IndexKeys.Ascending(i => i.Status).Ascending(i => i.ExpiresAt),
            new CreateIndexOptions { Name = "idx_invite_status_expires" })
    };

    public async ValueTask EnsureIndexesAsync(IMongoDatabase database, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(database);

        var collection = database.GetCollection<AuthorityBootstrapInviteDocument>(AuthorityMongoDefaults.Collections.Invites);
        await collection.Indexes.CreateManyAsync(Indexes, cancellationToken).ConfigureAwait(false);
    }
}
