using AutoMapper; using MediatR; using ExpenseTracker.Domain.Entities; using ExpenseTracker.Application.Common.Interfaces.Services; using ExpenseTracker.Domain.Enums; using ExpenseTracker.Application.Common.Interfaces; namespace ExpenseTracker.Application.Accounts.Commands.Create; public class CreateAccountCommandHandler : IRequestHandler { private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; private readonly ISessionUserService _sessionUserService; public CreateAccountCommandHandler( IMapper mapper, IUnitOfWork unitOfWork, ISessionUserService sessionUserService) { _mapper = mapper; _unitOfWork = unitOfWork; _sessionUserService = sessionUserService; } public async Task Handle(CreateAccountCommand request, CancellationToken cancellationToken) { // TODO: Add UserId validation. Throw ValidationException when there is no user with given UserId var parentUuid = Guid.NewGuid().ToString(); var childUuid = Guid.NewGuid().ToString(); var newAccount = new Account() { Id = parentUuid, Name = request.Name, Description = request.Description, Currency = Currency.FromName(request.Currency), UserId = request.UserId ?? _sessionUserService.Id }; var databaseAccount = await _unitOfWork.AccountRepository.AddOneAsync(newAccount, cancellationToken); var newTransaction = new Transaction() { Id = childUuid, Amount = request.InitialBalance, Category = Domain.Enums.Category.InitialBalance, Time = DateTimeOffset.UtcNow, AccountId = parentUuid }; var databaseTransaction = await _unitOfWork.TransactionRepository.AddOneAsync(newTransaction, cancellationToken); await _unitOfWork.SaveAsync(cancellationToken); return _mapper.Map(databaseAccount); } }