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

namespace StellaOps.Scanner.Storage.Repositories;

public sealed class LayerRepository
{
    private readonly MongoCollectionProvider _collections;

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

    public async Task UpsertAsync(LayerDocument document, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(document);
        document.LastSeenAtUtc = DateTime.UtcNow;
        var options = new ReplaceOptions { IsUpsert = true };
        await _collections.Layers
            .ReplaceOneAsync(x => x.LayerDigest == document.LayerDigest, document, options, cancellationToken)
            .ConfigureAwait(false);
    }

    public async Task<LayerDocument?> GetAsync(string layerDigest, CancellationToken cancellationToken)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(layerDigest);
        return await _collections.Layers
            .Find(x => x.LayerDigest == layerDigest)
            .FirstOrDefaultAsync(cancellationToken)
            .ConfigureAwait(false);
    }
}
