using MongoDB.Driver;
using StellaOps.Scanner.Storage.Catalog;
using StellaOps.Scanner.Storage.Mongo;

namespace StellaOps.Scanner.Storage.Repositories;

public sealed class LifecycleRuleRepository
{
    private readonly MongoCollectionProvider _collections;

    public LifecycleRuleRepository(MongoCollectionProvider collections)
    {
        _collections = collections ?? throw new ArgumentNullException(nameof(collections));
    }

    public async Task UpsertAsync(LifecycleRuleDocument document, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(document);
        document.CreatedAtUtc = document.CreatedAtUtc == default ? DateTime.UtcNow : document.CreatedAtUtc;
        var options = new ReplaceOptions { IsUpsert = true };
        await _collections.LifecycleRules
            .ReplaceOneAsync(x => x.Id == document.Id, document, options, cancellationToken)
            .ConfigureAwait(false);
    }

    public Task<List<LifecycleRuleDocument>> ListExpiredAsync(DateTime utcNow, CancellationToken cancellationToken)
    {
        var filter = Builders<LifecycleRuleDocument>.Filter.Lt(x => x.ExpiresAtUtc, utcNow);
        return _collections.LifecycleRules
            .Find(filter)
            .ToListAsync(cancellationToken);
    }
}
