namespace CMSMicroservice.Application.UserAddressCQ.Queries.GetAllUserAddressByFilter;
public class GetAllUserAddressByFilterQueryHandler : IRequestHandler<GetAllUserAddressByFilterQuery, GetAllUserAddressByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllUserAddressByFilterResponseDto> Handle(GetAllUserAddressByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.UserAddresses
            .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.Title == null || x.Title.Contains(request.Filter.Title))
                .Where(x => request.Filter.Address == null || x.Address.Contains(request.Filter.Address))
                .Where(x => request.Filter.PostalCode == null || x.PostalCode.Contains(request.Filter.PostalCode))
                .Where(x => request.Filter.IsDefault == null || x.IsDefault == request.Filter.IsDefault)
                .Where(x => request.Filter.CityId == null || x.CityId == request.Filter.CityId)
;
        }
        return new GetAllUserAddressByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query.PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllUserAddressByFilterResponseModel>().ToListAsync(cancellationToken)
        };        
    }
}
