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

namespace NetinaShop.Repository.Handlers.Brands;

public class GetBrandsQueryHandler : IRequestHandler<GetBrandsQuery, List<BrandSDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;

    public GetBrandsQueryHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }
    public async Task<List<BrandSDto>> Handle(GetBrandsQuery request, CancellationToken cancellationToken)
    {
        IQueryable<Brand> baseBrands;
        List<BrandSDto> brands = new List<BrandSDto>();
        if (request.CategoryId != default)
        {
            //var products = await _mediator.Send(new GetProductsQuery(BrandIds: null,SpecialOffer: null, Page:0, SortBy: QuerySortBy.None,CategoryId: request.CategoryId, IsActive : null),
            //    cancellationToken);
            var brandGrouped = _repositoryWrapper.SetRepository<Product>()
                .TableNoTracking
                .Where(p => p.CategoryId == request.CategoryId)
                .GroupBy(p=>p.BrandId);
            foreach (var grouping in brandGrouped)
            {
                if (grouping.Key != default)
                {
                    var brand = await _repositoryWrapper.SetRepository<Brand>()
                        .TableNoTracking
                        .Where(b => b.Id == grouping.Key)
                        .Select(BrandMapper.ProjectToSDto)
                        .FirstOrDefaultAsync(cancellationToken);
                    if(brand!=null)
                        brands.Add(brand);
                }
            }

            return brands;
        }

        if (request.BrandName != null)
        {
            baseBrands = _repositoryWrapper.SetRepository<Brand>()
                .TableNoTracking
                .Where(b => b.PersianName.Trim().Contains(request.BrandName.Trim()))
                .OrderByDescending(b => b.CreatedAt);
        }
        else
        {

            baseBrands = _repositoryWrapper.SetRepository<Brand>().TableNoTracking
                .OrderByDescending(b => b.CreatedAt);
        }

        if (request.Page != null)
        {
            brands = await baseBrands.Skip(request.Page.Value * 10).Take(10)
                .Select(BrandMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }
        else
        {

            brands = await baseBrands
                .Select(BrandMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }

        return brands;
    }
}