using Marten;

namespace NetinaShop.Infrastructure.Marten;

public class MartenRepository<TMartenEntity> : IMartenRepository<TMartenEntity> where TMartenEntity : IMartenEntity
{
    private readonly IDocumentStore _documentStore;

    public MartenRepository(IDocumentStore documentStore)
    {
        _documentStore = documentStore;
    }

    public async Task<List<TMartenEntity>> GetEntitiesAsync(CancellationToken cancellation)
    {
        await using var session = _documentStore.QuerySession();
        var entities = await session.Query<TMartenEntity>().ToListAsync(cancellation);
        return entities.ToList();
    }

    public async Task<List<TMartenEntity>> GetEntitiesAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation)
    {
        await using var session = _documentStore.QuerySession();
        var entities = await session.Query<TMartenEntity>().Where(expression).ToListAsync(cancellation);
        return entities.ToList();
    }

    public async Task<TMartenEntity> GetEntityAsync(Guid id, CancellationToken cancellation)
    {
        await using var session = _documentStore.QuerySession();
        var setting = await session.LoadAsync<TMartenEntity>(id, cancellation);
        if (setting == null)
            throw new AppException($"{nameof(setting)} not found", ApiResultStatusCode.NotFound);
        return setting;
    }

    public async Task<TMartenEntity?> GetEntityAsync(Expression<Func<TMartenEntity, bool>> expression, CancellationToken cancellation)
    {
        await using var session = _documentStore.QuerySession();
        var entity = await session.Query<TMartenEntity>().FirstOrDefaultAsync(expression, cancellation);
        return entity;
    }

    public async Task AddOrUpdateEntityAsync(TMartenEntity setting, CancellationToken cancellation)
    {
        if (setting == null)
            throw new AppException($"{nameof(setting)} is null", ApiResultStatusCode.BadRequest);

        await using var session = _documentStore.LightweightSession();
        session.Store(setting);
        await session.SaveChangesAsync(cancellation);
    }

    public Task RemoveEntityAsync(CancellationToken cancellation)
    {
        throw new NotImplementedException();
    }
}