namespace Netina.Core.CoreServices.SearchServices;

public class GetEmallsProductsQueryHandler(
    IRepositoryWrapper repositoryWrapper,
    IMediator mediator,
    IOptionsSnapshot<SiteSettings> optionsSnapshot)
    : IRequestHandler<GetEmallsProductsQuery, EmallsResponseDto>
{
    private readonly SiteSettings _siteSetting = optionsSnapshot.Value;

    public async Task<EmallsResponseDto> Handle(GetEmallsProductsQuery request, CancellationToken cancellationToken)
    {
        var page = request.Page;
        var productsSDto = await repositoryWrapper.SetRepository<Product>()
            .TableNoTracking
            .OrderByDescending(p => p.ModifiedAt == DateTime.MinValue ? p.CreatedAt : p.ModifiedAt)
            .Select(p => new ProductSDto
            {
                Id = p.Id,
                BeDisplayed = p.BeDisplayed,
                IsEnable = p.IsEnable,
                Cost = p.Cost,
                CategoryId = p.CategoryId,
                BrandId = p.BrandId,
                EnglishName = p.EnglishName,
                PersianName = p.PersianName,
                Slug = p.Slug,

            })
            .Skip(page * request.Count)
            .Take(request.Count)
            .ToListAsync(cancellationToken);


        foreach (var productSDto in productsSDto)
            await mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
        var products = new List<EmallsProductResponseDto>();
        foreach (var product in productsSDto)
        {
            var torobProduct = new EmallsProductResponseDto
            {
                is_available = product.IsEnable,
                url = $"{_siteSetting.WebSiteUrl}/products/{product.Id}/{product.Slug}",
                id = product.Id.ToString(),
                title = product.PersianName,
                category = product.CategoryName
            };
            if (product.Cost > product.CostWithDiscount)
            {
                torobProduct.old_price = (int)product.Cost / 10;
                torobProduct.price = (int)product.CostWithDiscount / 10;
            }
            else
                torobProduct.price = (int)product.Cost / 10;
            products.Add(torobProduct);
        }

        var response = new EmallsResponseDto();
        response.item_per_page = request.Count;
        response.page_num = request.Page;
        response.total_items = (await repositoryWrapper.SetRepository<Product>().TableNoTracking.CountAsync(cancellationToken));
        response.pages_count = response.total_items /  request.Count;
        response.products = products;

        return response;
    }
}