namespace CMSMicroservice.Application.OtpTokenCQ.Queries.GetAllOtpTokenByFilter;
public class GetAllOtpTokenByFilterQueryHandler : IRequestHandler<GetAllOtpTokenByFilterQuery, GetAllOtpTokenByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllOtpTokenByFilterResponseDto> Handle(GetAllOtpTokenByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.OtpTokens
            .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.Mobile == null || x.Mobile.Contains(request.Filter.Mobile))
                .Where(x => request.Filter.Purpose == null || x.Purpose.Contains(request.Filter.Purpose))
                .Where(x => request.Filter.CodeHash == null || x.CodeHash.Contains(request.Filter.CodeHash))
                .Where(x => request.Filter.ExpiresAt == null || x.ExpiresAt == request.Filter.ExpiresAt)
                .Where(x => request.Filter.Attempts == null || x.Attempts == request.Filter.Attempts)
                .Where(x => request.Filter.IsUsed == null || x.IsUsed == request.Filter.IsUsed)
;
        }
        return new GetAllOtpTokenByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllOtpTokenByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
