using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Blogs;

namespace Netina.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 response = new GetBlogsResponseDto();
        int count = 20;
        if (request.Count != null)
            count = request.Count.Value;
        var query = _repositoryWrapper.SetRepository<Blog>().TableNoTracking;
        if (request.CategoryId != null)
            query = query.Where(b => b.CategoryId == request.CategoryId);
        if (request.BlogName != null)
            query = query.Where(b => b.Title.Trim().ToUpper().Contains(request.BlogName.Trim().ToUpper()));

        var result = await query
            .OrderByDescending(b => b.CreatedAt)
            .Skip(request.Page * count).Take(count)
            .Select(BlogMapper.ProjectToSDto).ToListAsync(cancellationToken);
        response.Pager.CurrentPage = request.Page;
        response.Pager.TotalItems = await query.CountAsync(cancellationToken);
        response.Pager.TotalPage = response.Pager.TotalItems % 20 == 0 ? response.Pager.TotalItems / 20 : (response.Pager.TotalItems / 20) + 1;

        response.Blogs = result;

        return response;
    }
}