using AutoMapper; using MediatR; using ExpenseTracker.Application.Common.Exceptions; using ExpenseTracker.Application.Common.Interfaces; using ExpenseTracker.Domain.Entities; namespace ExpenseTracker.Application.Accounts.Commands.Update; public class UpdateAccountCommandHandler : IRequestHandler { private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public UpdateAccountCommandHandler(IMapper mapper, IUnitOfWork unitOfWork) { _mapper = mapper; _unitOfWork = unitOfWork; } public async Task Handle(UpdateAccountCommand request, CancellationToken cancellationToken) { var databaseEntity = _unitOfWork.AccountRepository.Queryable.FirstOrDefault(e => e.Id == request.Id); if (databaseEntity == null) { throw new NotFoundException(); } // TODO: Add UserId validation. Throw NotFoundException when there is no user with given UserId var updatedEntity = new Account() { Id = request.Id, Name = request.Name ?? databaseEntity.Name, Description = request.Description, UserId = request.UserId }; databaseEntity = await _unitOfWork.AccountRepository.UpdateOneAsync(updatedEntity, cancellationToken); await _unitOfWork.SaveAsync(cancellationToken); return _mapper.Map(databaseEntity); } }