namespace CMSMicroservice.Application.TagCQ.Queries.GetAllTagByFilter;
public class GetAllTagByFilterQueryHandler : IRequestHandler<GetAllTagByFilterQuery, GetAllTagByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllTagByFilterResponseDto> Handle(GetAllTagByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Tags
            .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.IsActive == null || x.IsActive == request.Filter.IsActive)
                .Where(x => request.Filter.SortOrder == null || x.SortOrder == request.Filter.SortOrder)
;
        }
        return new GetAllTagByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllTagByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}

