using Netina.Domain.Entities.ProductCategories;

namespace Netina.Core.CoreServices.SearchServices;

public class GetThumbSearchProductsQueryHandler(IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<GetThumbSearchProductsQuery, SearchResponseDto>
{
    public async Task<SearchResponseDto> Handle(GetThumbSearchProductsQuery request, CancellationToken cancellationToken)
    {

        var searchQuery = request.Name;

        var products = await repositoryWrapper.SetRepository<Product>()
            .TableNoTracking
            .OrderByDescending(p => EF.Functions.TrigramsSimilarity(p.PersianName, searchQuery))
            .Take(8)
            .Select(ProductMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

        var categories = await repositoryWrapper.SetRepository<ProductCategory>()
            .TableNoTracking
            .OrderByDescending(p => EF.Functions.TrigramsSimilarity(p.Name.ToLower().Trim(), searchQuery))
            .Take(8)
            .Select(ProductCategoryMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

        return new SearchResponseDto
        {
            Products = products.Select(p => p.Adapt<SearchedProductResponseDto>()).ToList(),
            Categories = categories.Select(c => c.Adapt<SearchedProductCategoryResponseDto>()).ToList()
        };
    }
}