namespace CMSMicroservice.Application.PackageCQ.Queries.GetAllPackageByFilter;
public class GetAllPackageByFilterQueryHandler : IRequestHandler<GetAllPackageByFilterQuery, GetAllPackageByFilterResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllPackageByFilterResponseDto> Handle(GetAllPackageByFilterQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Packages
            .Where(x => !x.IsDeleted)
            .ApplyOrder(sortBy: request.SortBy)
            .AsNoTracking()
            .Include(x => x.PackageFeatures)
            .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.ImagePath == null || x.ImagePath.Contains(request.Filter.ImagePath))
                .Where(x => request.Filter.Price == null || x.Price == request.Filter.Price)
;
        }
        var packages = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .ToListAsync(cancellationToken);

        var models = packages.Select(p =>
        {
            var model = p.Adapt<GetAllPackageByFilterResponseModel>();
            model.FeatureIds = p.PackageFeatures?
                .Where(pf => pf.IsIncluded)
                .Select(pf => pf.ClubFeatureId)
                .ToList() ?? new();
            return model;
        }).ToList();

        return new GetAllPackageByFilterResponseDto
        {
            MetaData = await query.GetMetaData(request.PaginationState, cancellationToken),
            Models = models
        };        
    }
}
