using NetinaCMS.Repository.Repositories.Base.Contracts;

namespace NetinaCMS.Repository.Handlers.Blogs;

public class GetBlogsQueryHandler : IRequestHandler<GetBlogsQuery,GetBlogsResponseDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetBlogsQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<GetBlogsResponseDto> Handle(GetBlogsQuery request, CancellationToken cancellationToken)
    {
        var originals = _repositoryWrapper.SetRepository<Blog>()
            .TableNoTracking;

        var blogs = await originals.Skip(request.Page * 20)
            .Take(20)
            .Select(BlogMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

        var response = new GetBlogsResponseDto();
        response.Blogs = blogs;
        response.Pager.CurrentPage = request.Page;
        response.Pager.TotalItems = await originals.CountAsync(cancellationToken);
        response.Pager.TotalPage = response.Pager.TotalItems / 20;

        return response;
    }
}