using Microsoft.Extensions.Logging.Abstractions;
using MongoDB.Bson;
using StellaOps.Feedser.Storage.Mongo.Dtos;

namespace StellaOps.Feedser.Storage.Mongo.Tests;

[Collection("mongo-fixture")]
public sealed class DtoStoreTests : IClassFixture<MongoIntegrationFixture>
{
    private readonly MongoIntegrationFixture _fixture;

    public DtoStoreTests(MongoIntegrationFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public async Task UpsertAndLookupDto()
    {
        var store = new DtoStore(_fixture.Database, NullLogger<DtoStore>.Instance);
        var record = new DtoRecord(
            Guid.NewGuid(),
            Guid.NewGuid(),
            "source",
            "1.0",
            new BsonDocument("value", 1),
            DateTimeOffset.UtcNow);

        var upserted = await store.UpsertAsync(record, CancellationToken.None);
        Assert.Equal(record.DocumentId, upserted.DocumentId);

        var fetched = await store.FindByDocumentIdAsync(record.DocumentId, CancellationToken.None);
        Assert.NotNull(fetched);
        Assert.Equal(1, fetched!.Payload["value"].AsInt32);

        var bySource = await store.GetBySourceAsync("source", 10, CancellationToken.None);
        Assert.Single(bySource);
        Assert.Equal(record.DocumentId, bySource[0].DocumentId);
    }
}
