using FluentValidation;
using Shared.DTOs.Warehouse;
using Back.Data.Models.Warehouse;
using Back.Data.Contracts;
using Back.Services.Warehouse;
using Back.Services;
using Microsoft.EntityFrameworkCore;

namespace Back.Validations.Warehouse.Receipt
{
    public class DeleteValidation : AbstractValidator<Tuple<int, int>>
    {
        public DeleteValidation(IAsyncRepository<Back.Data.Models.Warehouse.Receipt> _ReceiptRepo, WarehouseService warehouseService)
        {
            RuleFor(model => model)
                .Custom((model, context) =>
                {
                    var ORGitem = _ReceiptRepo.Get(w => w.ID == model.Item1 && w.cODItem.CompanyID == model.Item2 && !w.Deleted).Include(i => i.cODItem).FirstOrDefault();
                    if (ORGitem == null)
                        context.AddFailure("رسید یافت نشد");
                    
                    var Inventory = warehouseService.Inventory(model.Item2, ORGitem.CODID).Result;
                    if (Inventory - ORGitem.Count < 0)
                    {
                        context.AddFailure($"حذف رسید روی موجودی کالا {ORGitem.cODItem.Title} تاثیر میگذارد و آن را منفی میکند");
                    }
                });
        }
    }
}
