using Microsoft.EntityFrameworkCore;
using NetinaShop.Domain.Entities.ProductCategories;

namespace NetinaShop.Repository.Handlers.ProductCategories;

public class GetProductCategoriesQueryHandler : IRequestHandler<GetProductCategoriesQuery, List<ProductCategorySDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetProductCategoriesQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<List<ProductCategorySDto>> Handle(GetProductCategoriesQuery request, CancellationToken cancellationToken)
    {
        IQueryable<ProductCategory> basCategories;
        List<ProductCategorySDto> groupCats;
        if (request.CategoryName != null)
        {
            basCategories = _repositoryWrapper.SetRepository<ProductCategory>()
                .TableNoTracking
                .Where(c => c.Name.Trim().Contains(request.CategoryName.Trim()))
                .OrderByDescending(c => c.CreatedAt);
        }
        else
        {

            basCategories = _repositoryWrapper.SetRepository<ProductCategory>()
                .TableNoTracking
                .OrderByDescending(c=>c.CreatedAt);
        }
        if (request.Page != null)
        {
            groupCats = await basCategories
                .Skip(request.Page.Value * 15).Take(15)
                .Select(ProductCategoryMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }
        else
        {
            groupCats = await basCategories
                .Select(ProductCategoryMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }

        if (request.SortByMain == null || !request.SortByMain.Value)
            return groupCats;

        foreach (var cat in groupCats)
            cat.Children = groupCats.Where(c => c.ParentId == cat.Id).ToList();

        var cats = groupCats.Where(c => c.IsMain).ToList();
        return cats;

    }
}