namespace CMSMicroservice.Application.ContractCQ.Queries.GetAllContractByFilter;
public class GetAllContractByFilterQueryHandler : IRequestHandler<GetAllContractByFilterQuery, GetAllContractByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllContractByFilterResponseDto> Handle(GetAllContractByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Contracts
            .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.HtmlContent == null || x.HtmlContent.Contains(request.Filter.HtmlContent))
                .Where(x => request.Filter.Type == null || x.Type == request.Filter.Type)
;
        }
        return new GetAllContractByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllContractByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
