namespace Netina.Core.EntityServices.OrderBagHandlers;

public class CheckOrderBagCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator)
    : IRequestHandler<CheckOrderBagCommand, List<CheckOrderBagResponseItem>>
{
    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;
    }
}