using Microsoft.Extensions.DependencyInjection;
using OpenHarbor.CQRS.DynamicQuery.Abstractions;

namespace Codex.Dal;

public class DefaultQueryableProvider<TEntity>(CodexDbContext context, IServiceProvider serviceProvider) : IQueryableProvider<TEntity>
  where TEntity : class
{
    public Task<IQueryable<TEntity>> GetQueryableAsync(object query, CancellationToken cancellationToken = default)
    {
        if (serviceProvider.GetService(typeof(IQueryableProviderOverride<TEntity>)) is IQueryableProviderOverride<TEntity> queryableProviderOverride)
            return queryableProviderOverride.GetQueryableAsync(query, cancellationToken);

        return Task.FromResult(context.Set<TEntity>().AsQueryable());
    }
}
