using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace StellaOps.Feedser.Storage.Mongo.JpFlags;

public sealed class JpFlagStore : IJpFlagStore
{
    private readonly IMongoCollection<JpFlagDocument> _collection;
    private readonly ILogger<JpFlagStore> _logger;

    public JpFlagStore(IMongoDatabase database, ILogger<JpFlagStore> logger)
    {
        ArgumentNullException.ThrowIfNull(database);
        ArgumentNullException.ThrowIfNull(logger);

        _collection = database.GetCollection<JpFlagDocument>(MongoStorageDefaults.Collections.JpFlags);
        _logger = logger;
    }

    public async Task UpsertAsync(JpFlagRecord record, CancellationToken cancellationToken)
    {
        ArgumentNullException.ThrowIfNull(record);

        var document = JpFlagDocumentExtensions.FromRecord(record);
        var filter = Builders<JpFlagDocument>.Filter.Eq(x => x.AdvisoryKey, record.AdvisoryKey);
        var options = new ReplaceOptions { IsUpsert = true };
        await _collection.ReplaceOneAsync(filter, document, options, cancellationToken).ConfigureAwait(false);
        _logger.LogDebug("Upserted jp_flag for {AdvisoryKey}", record.AdvisoryKey);
    }

    public async Task<JpFlagRecord?> FindAsync(string advisoryKey, CancellationToken cancellationToken)
    {
        ArgumentException.ThrowIfNullOrEmpty(advisoryKey);

        var filter = Builders<JpFlagDocument>.Filter.Eq(x => x.AdvisoryKey, advisoryKey);
        var document = await _collection.Find(filter).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
        return document?.ToRecord();
    }
}
