Api/Netina.Repository/Handlers/Comments/DeleteCommentCommandHandler.cs

35 lines
1.5 KiB
C#

namespace Netina.Repository.Handlers.Comments;
public class DeleteCommentCommandHandler(IRepositoryWrapper repositoryWrapper)
: IRequestHandler<DeleteCommentCommand, Guid>
{
public async Task<Guid> Handle(DeleteCommentCommand request, CancellationToken cancellationToken)
{
var review = await repositoryWrapper.SetRepository<Comment>().TableNoTracking
.FirstOrDefaultAsync(r => r.Id == request.Id, cancellationToken);
if (review == null)
throw new AppException("Comment not found", ApiResultStatusCode.NotFound);
if (review.IsConfirmed)
{
var productComment = await repositoryWrapper.SetRepository<ProductComment>()
.TableNoTracking.FirstOrDefaultAsync(f => f.Id == request.Id, cancellationToken);
if (productComment != null)
{
var product = await repositoryWrapper.SetRepository<Product>()
.TableNoTracking
.FirstOrDefaultAsync(p => p.Id == productComment.ProductId, cancellationToken);
if (product != null)
{
product.RemoveRate(review.Rate);
repositoryWrapper.SetRepository<Product>().Update(product);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
}
}
}
repositoryWrapper.SetRepository<Comment>().Delete(review);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return review.Id;
}
}