namespace CMSMicroservice.Application.PackageCQ.Queries.GetAllPackageByFilter;
public class GetAllPackageByFilterQueryHandler : IRequestHandler<GetAllPackageByFilterQuery, GetAllPackageByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllPackageByFilterResponseDto> Handle(GetAllPackageByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Packages
            .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.Title == null || x.Title.Contains(request.Filter.Title))
                .Where(x => request.Filter.Description == null || x.Description.Contains(request.Filter.Description))
                .Where(x => request.Filter.ImagePath == null || x.ImagePath.Contains(request.Filter.ImagePath))
                .Where(x => request.Filter.Price == null || x.Price == request.Filter.Price)
;
        }
        return new GetAllPackageByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllPackageByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
