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)
    {
        var groupCats = await _repositoryWrapper.SetRepository<ProductCategory>()
            .TableNoTracking
            .Select(CategoryMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

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

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

        return mainCats;
    }
}