DeleteChargingPileCommandHandler.cs 1.73 KB
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands.ChargingPile;
using Rcs.Domain.Repositories;

namespace Rcs.Infrastructure.MessageBus.Handlers.Commands.ChargingPile
{
    /// <summary>
    /// Delete charging pile command handler.
    /// </summary>
    public class DeleteChargingPileCommandHandler : IConsumer<DeleteChargingPileCommand>
    {
        private readonly ILogger<DeleteChargingPileCommandHandler> _logger;
        private readonly IChargingPileRepository _repository;

        public DeleteChargingPileCommandHandler(
            ILogger<DeleteChargingPileCommandHandler> logger,
            IChargingPileRepository repository)
        {
            _logger = logger;
            _repository = repository;
        }

        public async Task Consume(ConsumeContext<DeleteChargingPileCommand> context)
        {
            var command = context.Message;

            try
            {
                var entity = await _repository.GetByIdAsync(command.PileId, context.CancellationToken);
                if (entity == null)
                {
                    await context.RespondAsync(ApiResponse.Failed($"Charging pile not found: {command.PileId}"));
                    return;
                }

                await _repository.DeleteAsync(entity, context.CancellationToken);
                await _repository.SaveChangesAsync(context.CancellationToken);

                await context.RespondAsync(ApiResponse.Successful());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Delete charging pile failed");
                await context.RespondAsync(ApiResponse.Failed(ex.Message));
            }
        }
    }
}