using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.TransactionsCQ.Commands.UpdateTransactions;
public class UpdateTransactionsCommandHandler : IRequestHandler<UpdateTransactionsCommand, Unit>
{
    private readonly IApplicationDbContext _context;

    public UpdateTransactionsCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Unit> Handle(UpdateTransactionsCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Transactions
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(Transaction), request.Id);
        request.Adapt(entity);
        _context.Transactions.Update(entity);
        entity.AddDomainEvent(new UpdateTransactionsEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
