using Common.Dtos.Common;
using Microsoft.EntityFrameworkCore;

namespace Api.Extensions;

public static class PagingExtensions
{
    public static async Task<PagedList<T>> ToPagedListAsync<T>(this IQueryable<T> queryable, int pageNumber, int pageSize)
    {
        var query = queryable;
        int totalItemsCount = await queryable.CountAsync();
        int totalPagesCount = (totalItemsCount / pageSize) + 1;
        var number = Math.Min(pageNumber, totalPagesCount);
        int skip = (number - 1) * pageSize;

        var items = await query.Skip(skip).Take(pageSize).ToArrayAsync();
        return new PagedList<T>(items, pageNumber, pageSize, totalItemsCount, totalPagesCount);
    }
}
