using Netina.Domain.Dtos.ResponseDtos.Torob;

namespace Netina.Core.CoreServices.SearchServices;

public class GetTorobProductsQueryHandler : IRequestHandler<GetTorobProductsQuery, List<TorobProductResponseDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;
    private readonly SiteSettings _siteSetting;

    public GetTorobProductsQueryHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator, IOptionsSnapshot<SiteSettings> optionsSnapshot)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
        _siteSetting = optionsSnapshot.Value;
    }
    public async Task<List<TorobProductResponseDto>> Handle(GetTorobProductsQuery request, CancellationToken cancellationToken)
    {
        int page = request.Page == 0 ? 1 : 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 * 100)
            .Take(100)
            .ToListAsync(cancellationToken);


        foreach (var productSDto in productsSDto)
            await _mediator.Send(new CalculateProductDiscountCommand(productSDto), cancellationToken);
        var products = new List<TorobProductResponseDto>();
        foreach (var product in productsSDto)
        {
            var torobProduct = new TorobProductResponseDto
            {
                availibility = product.IsEnable,
                page_url = $"{_siteSetting.WebSiteUrl}/products/{product.Id}",
                product_id = product.Id.ToString()
            };
            if (product.Cost > product.CostWithDiscount)
            {
                torobProduct.old_price = product.Cost;
                torobProduct.price = product.CostWithDiscount;
            }
            else
                torobProduct.price = product.Cost;
            products.Add(torobProduct);
        }

        return products;
    }
}