namespace CMSMicroservice.Application.CategoryCQ.Queries.GetAllCategoryByFilter;
public class GetAllCategoryByFilterQueryHandler : IRequestHandler<GetAllCategoryByFilterQuery, GetAllCategoryByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllCategoryByFilterResponseDto> Handle(GetAllCategoryByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Categories
            .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.Name == null || x.Name.Contains(request.Filter.Name))
                .Where(x => request.Filter.Title == null || x.Title.Contains(request.Filter.Title))
                .Where(x => request.Filter.Description == null || (x.Description != null && x.Description.Contains(request.Filter.Description)))
                .Where(x => request.Filter.ImagePath == null || (x.ImagePath != null && x.ImagePath.Contains(request.Filter.ImagePath)))
                .Where(x => request.Filter.ParentId == null || x.ParentId == request.Filter.ParentId)
                .Where(x => request.Filter.IsActive == null || x.IsActive == request.Filter.IsActive)
                .Where(x => request.Filter.SortOrder == null || x.SortOrder == request.Filter.SortOrder)
;
        }
        return new GetAllCategoryByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .Select(x => new GetAllCategoryByFilterResponseModel
                {
                    Id = x.Id,
                    Name = x.Name,
                    Title = x.Title,
                    Description = x.Description,
                    ImagePath = x.ImagePath,
                    ParentId = x.ParentId,
                    IsActive = x.IsActive,
                    SortOrder = x.SortOrder,
                    ProductCount = x.ProductCategories.Count
                }).ToListAsync(cancellationToken)
        };        
    }
}

