using DataSharing.Share.Requests;
using SqlSugar;

namespace DataSharing.Repository.Extensions
{
    public static class SqlSugarRepositoryExtensions
    {
        public static async Task<(int Total, List<TEntity> Items)> ToPagedListAsync<TEntity>(this ISugarQueryable<TEntity> query, int pageIndex, int pageSize, CancellationToken cancellationToken = default)
            where TEntity : class, new()
        {
            RefAsync<int> total = 0;
            var items = await query.ToPageListAsync(pageIndex, pageSize, total);
            return (total.Value, items);
        }

        public static async Task<(int Total, List<TEntity> Items)> ToPagedListAsync<TEntity>(this ISugarQueryable<TEntity> query, PagedRequest dto, CancellationToken cancellationToken = default)
            where TEntity : class, new()
        {
            RefAsync<int> total = 0;
            var items = await query.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
            return (total.Value, items);
        }

        public static Task<List<TEntity>> ToFixedListAsync<TEntity>(this ISugarQueryable<TEntity> query, int queryIndex, int? queryCount = null, CancellationToken cancellationToken = default)
          where TEntity : class, new()
        {
            if (queryCount is null or 0) queryCount = 50;
            return query.Skip(queryIndex * queryCount.Value).Take(queryCount.Value).ToListAsync(cancellationToken);
        }
    }
}
