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

namespace StellaOps.Scanner.Storage.Repositories;

public sealed class ImageRepository
{
    private readonly MongoCollectionProvider _collections;

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

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

    public async Task<ImageDocument?> GetAsync(string imageDigest, CancellationToken cancellationToken)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(imageDigest);
        return await _collections.Images
            .Find(x => x.ImageDigest == imageDigest)
            .FirstOrDefaultAsync(cancellationToken)
            .ConfigureAwait(false);
    }
}
