using Common.Security.Interfaces; using MediatR; using Modules.Media.Api.Commands; using Modules.User.Application.Interfaces; using Modules.User.Application.Repositories; namespace Modules.User.Application.Commands.User; public class DeleteUserAvatarCommand : IRequest { } public class DeleteUserAvatarCommandHandler(IUserContext userContext, IUserRepository userRepository, IMediator mediator, IUnitOfWork unitOfWork) : IRequestHandler { public async Task Handle(DeleteUserAvatarCommand request, CancellationToken cancellationToken) { var accountId = userContext.GetAccountId(); if (!accountId.HasValue) return Unit.Value; //TODO: if (!accountId.HasValue) throw new UnauthorizedAccessException("AccountId not found"); var user = await userRepository.GetByAccountIdAsync(accountId.Value, cancellationToken); if (user == null) return Unit.Value; //TODO: if (user == null) throw new UserNotFoundException(); //"User not found" if (user.Avatar != null) { var deleted = await mediator.Send(new DeleteObjectCommand { BucketName = "my-bookmark.user", ObjectName = user.Avatar.Id, }, cancellationToken); if (!deleted) { //TODO: log error //throw new Exception("Failed to delete avatar from storage"); return Unit.Value; } user.SetAvatar(null); } await userRepository.SaveAsync(user, cancellationToken); await unitOfWork.SaveChangesAsync(cancellationToken); return Unit.Value; } }