using MyWarehouse.Application.Common.Dependencies.DataAccess; using MyWarehouse.Application.Common.Exceptions; using MyWarehouse.Domain.Products; namespace MyWarehouse.Application.Products; public record FlashSaleCommand : IRequest, IMessage { public int Id { get; init; } public decimal PriceAmount { get; init; } public int DurationDays { get; set; } = 1; } public class FlashSaleCommandHandler : IRequestHandler<FlashSaleCommand> { private readonly IUnitOfWork _unitOfWork; private readonly IMessageSession _messageSession; public FlashSaleCommandHandler(IUnitOfWork unitOfWork, IMessageSession messageSession) { _unitOfWork = unitOfWork; _messageSession = messageSession; } public async Task<Unit> Handle(FlashSaleCommand request, CancellationToken cancellationToken) { var product = await _unitOfWork.Products.GetByIdAsync(request.Id) ?? throw new EntityNotFoundException(nameof(Product), request.Id); product.FlashSale(request.PriceAmount, TimeSpan.FromDays(request.DurationDays)); await _unitOfWork.SaveChanges(); foreach (var evnt in product.GetUncommittedEvents()) { await _messageSession.Publish(evnt); } return Unit.Value; } }