namespace Netina.Repository.Handlers.ProductCategories;

public class GetProductCategoryChildrenQueryHandler(IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<GetProductCategoryChildrenQuery, List<Guid>>
{
    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;
    }
}