namespace CMSMicroservice.Application.UserContractCQ.Queries.GetAllUserContractByFilter;
public class GetAllUserContractByFilterQueryHandler : IRequestHandler<GetAllUserContractByFilterQuery, GetAllUserContractByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllUserContractByFilterResponseDto> Handle(GetAllUserContractByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserContracts
            .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.UserId == null || x.UserId == request.Filter.UserId)
                .Where(x => request.Filter.ContractId == null || x.ContractId == request.Filter.ContractId)
                .Where(x => request.Filter.SignGuid == null || x.SignGuid.Contains(request.Filter.SignGuid))
                .Where(x => request.Filter.SignedPdfFile == null || x.SignedPdfFile.Contains(request.Filter.SignedPdfFile))
;
        }
        return new GetAllUserContractByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllUserContractByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
