using Netina.Domain.CommandQueries.Commands;
using Netina.Domain.Dtos.ResponseDtos;
using Netina.Domain.Entities.Products;
using Netina.Repository.Repositories.Base.Contracts;

namespace Netina.Core.EntityServices.OrderBagHandlers;

public class CheckOrderBagCommandHandler : IRequestHandler<CheckOrderBagCommand , List<CheckOrderBagResponseItem>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;

    public CheckOrderBagCommandHandler(IRepositoryWrapper repositoryWrapper,IMediator mediator)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
    }
    public async Task<List<CheckOrderBagResponseItem>> Handle(CheckOrderBagCommand request, CancellationToken cancellationToken)
    {
        List<CheckOrderBagResponseItem> response = new List<CheckOrderBagResponseItem>();

        foreach (var item in request.OrderBag)
        {
            var product = await _repositoryWrapper.SetRepository<Product>()
                .TableNoTracking
                .Where(p => p.Id == item.ProductId)
                .Select(ProductMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);

            if (product == null)
            {
                response.Add(new CheckOrderBagResponseItem
                {
                    Count = item.Count,
                    IsEnable = false,
                    IsRemoved = true,
                    ProductId = item.ProductId,
                    Stock = 0
                });
            }
            else
            {
                await _mediator.Send(new CalculateProductDiscountCommand(product), cancellationToken);
                var res = new CheckOrderBagResponseItem
                {
                    ProductId = item.ProductId,
                    CostWithDiscount = product.CostWithDiscount,
                    Cost = product.Cost,
                    DiscountPercent = product.DiscountPercent,
                    ProductName = product.PersianName,
                    Stock = product.Stock,
                    Count = item.Count,
                    IsEnable = product.IsEnable,
                    IsRemoved = false
                };
                response.Add(res);
            }
        }

        return response;
    }
}