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

namespace StellaOps.Scanner.Storage.Repositories;

public sealed class LinkRepository
{
    private readonly MongoCollectionProvider _collections;

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

    public async Task UpsertAsync(LinkDocument document, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(document);
        var options = new ReplaceOptions { IsUpsert = true };
        await _collections.Links
            .ReplaceOneAsync(x => x.Id == document.Id, document, options, cancellationToken)
            .ConfigureAwait(false);
    }

    public Task<List<LinkDocument>> ListBySourceAsync(LinkSourceType type, string digest, CancellationToken cancellationToken)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(digest);
        return _collections.Links
            .Find(x => x.FromType == type && x.FromDigest == digest)
            .ToListAsync(cancellationToken);
    }
}
