using MediatR;
using System.Threading;
using Microsoft.EntityFrameworkCore;

namespace NetinaShop.Repository.Handlers.ProductCategories;

public class GetProductCategoryChildrenQueryHandler : IRequestHandler<GetProductCategoryChildrenQuery,List<Guid>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetProductCategoryChildrenQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }

    public async Task<List<Guid>> Handle(GetProductCategoryChildrenQuery request, CancellationToken cancellationToken)
    {
        if (request.Id == default)
            throw new AppException("Category id is null");

        return await Recursive(request.Id, cancellationToken);

    }

    private async Task<List<Guid>> Recursive(Guid id,CancellationToken cancellationToken)
    {

        var children = await _repositoryWrapper.SetRepository<ProductCategory>()
        .TableNoTracking
            .Where(c => c.ParentId == id)
            .Select(c => c.Id)
            .ToListAsync(cancellationToken);
        var returnList = new List<Guid> { id };
        if (children.Count > 0)
        {
            foreach (var child in children)
            {
                var chs = await Recursive(child,cancellationToken);
                chs.ForEach(c=>returnList.Add(c));
            }

            return returnList;
        }
        else
            return returnList;
    }
}