using CMSMicroservice.Application.Common.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.CityCQ.Queries.GetAllCitiesByFilter;

public class GetAllCitiesByFilterQueryHandler : IRequestHandler<GetAllCitiesByFilterQuery, GetAllCitiesByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllCitiesByFilterResponseDto> Handle(
        GetAllCitiesByFilterQuery request, 
        CancellationToken cancellationToken)
    {
        var query = _context.Cities
            .Include(c => c.State)
            .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.Name == null || x.Name.Contains(request.Filter.Name))
                .Where(x => request.Filter.Native == null || x.Native.Contains(request.Filter.Native))
                .Where(x => request.Filter.StateId == null || x.StateId == request.Filter.StateId);
        }
        
        return new GetAllCitiesByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = await query
                .PaginatedListAsync(paginationState: request.PaginationState)
                .ProjectToType<GetAllCitiesByFilterResponseModel>()
                .ToListAsync(cancellationToken)
        };
    }
}
