namespace CMSMicroservice.Application.UserCartsCQ.Queries.GetAllUserCartsByFilter;
public class GetAllUserCartsByFilterQueryHandler : IRequestHandler<GetAllUserCartsByFilterQuery, GetAllUserCartsByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetAllUserCartsByFilterQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetAllUserCartsByFilterResponseDto> Handle(GetAllUserCartsByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserCarts.Include(i=>i.Product)
            .ApplyOrder(sortBy: request.SortBy)
            .AsNoTracking()
            .AsQueryable();
        if (request.Filter is not null)
        {
            query = query
                .Where(x => request.Filter.Id == null || x.Id == request.Filter.Id)
                .Where(x => request.Filter.ProductId == null || x.ProductId == request.Filter.ProductId)
                .Where(x => request.Filter.UserId == null || x.UserId == request.Filter.UserId)
                .Where(x => request.Filter.Count == null || x.Count == request.Filter.Count)
;
        }
        return new GetAllUserCartsByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllUserCartsByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
